I have this rather simple Ruby on Rails application : two models Lists
and Items
. Lists
have many Items
and Items
belong to Lists
. OK.
The show
method of ListsController
prints a page with the list of the items belonging to the given list (in a partial lists/_listOfItems.html.erb
). At the end of the show.html.erb
view, there is a form that lets users add an item to the list. In standard (no jQuery) RoR, this works perfectly.
Now, what I want to do is let user add an item to the list without reloading the page. I have managed with jQuery to add the item to the database but now my problem is to refresh the html list without reloading the page. I have managed to have a create.js.erb
executed in ItemsController
and I can make things appear on the page with it but the problem is that this create.js.erb
lives in ItemsController
and not in ListsController
so that if I try to make create.js.erb
render the partial _listOfItems.html.erb
, it will fail since create.js.erb
lives in ItemsController
and hence cannot access the variables defined in the show
method of ListsController
.
I guess it would work like a charm if I was using the index
method of ItemsController
to display the list of items since everything would be living in there but that might yield further complications.
I hope that was clear. Can you help me? Thank you very much!
If I understand right I think the solution lies in javascript + an action in your controller:
your show view should have an ajax call as follows, this should be triggered by a click/change/... jquery function, for example: $("selector").change(function() { here the ajax call is placed })
$.ajax( {
type: 'get',
url: "/ajax/somepageofyourown",
async: false,
data: { add here any variables your controller method would need },
success: function( r ) {
$(' the selector that needs to be replaced ').html( r );
}
} );
add the url that this ajax calls to your routes, so that your controller responds
add your controller action, it should trigger that renders the html that you want to replace the previous html with.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.