You can add the
remote: true parameter to any
form_for. Behind the scenes, rails will do some magic to make that link, when clicked, fire off an XHR HTTP request to whatever action you specified. The request gets sent to the controller in your rails application just like it normally would - adding
remote: true doesn’t change which parameters get sent, or how they’re formatted, just whether they are sent with AJAX or a regular, page-refreshing HTTP request.
The only difference in the controller is that instead of returning html via the
format.js block. As such, the template that will be rendered won’t be (for example)
/show.html.erb, it’ll be
What’s the easiest way to make use of this? The easiest way is to use your
.js.erb file to render a partial and replace the element on the page with your rendered partial. Let’s say you have a partial called
_item.html.erb which renders an
Item object. Suppose that on some page somewhere you have a ‘featured item’ display that calls
<%= render "item", item: @item %>, which renders your
_item.html.erb partial. You want to be able to refresh it to re-render the same item with a button.
Your featured item display might look like this:
1 2 3
Your link will look like this (of course, you can add any styling
class: and such that you like):
What should we put in
show.js.erb? This will work:
This will call the
.html method, which replaces the inner html of the target element with its argument. The
render "item" does exactly what it always does, rendering a partial into a string of html.
That’s it. Now when you click the ‘refresh’ link, it’ll replace the content of
#featured-item with the appropriate new content. Hooray, AJAX!