Ajax requests for partial renders for Ruby on Rails


  • Ruby on Rails installed
  • Basic project created
  • Basic knowledge on Ruby on Rails


Consider the basic scenario…

You have one div in the view you wish to be refreshed with different content when a button is clicked however you do not with the entire page to be redrawn.

So in my index method one could have:

# /controller/movie_controller.rb
def index
  @movie = Movie.first

And for simplicity sake, the view for this controller could be:

# /views/movie/index.html
<%= render partial: "movie_media_box", locals: {movie: @movie} %>

This renders the html located in the “/views/movie/_movie_media_box.html.erb here and passes it the “movie” variable. A basic partial to be changed would look like:

# /views/movie/_movie_media_box.html.erb
<div id=movie-<%=movie.id%>>

Now, the button you wish to trigger the changing of this div should look something like:

# Anywhere you want it
<%= link_to "change", {:controller => "movies", :action => "change_movie", :id => movie.id}, :remote => true%>

What this is doing is creating a link which will call the “change_movie” method in the “movies” controller passing it “id” as a parameter. The “remote =>true” is letting rails know to handle this as a ajax request.

The “change_movie” method should look similar to:

# /controller/movie_controller.rb
def change_movie
  @previous_id = params["id"]
  @new_movie = Movie.last
  respond_to do |format|

Notice how this is not returning a html file, instead it is returning a JS file which is named “/views/movie/change_movie.js.erb”. In this file is where will be changing the content of that div.

# /views/movie/change_movie.js.erb
$("#movie-<%=@previous_id%>").html("<%= escape_javascript(render partial: 'movie_media_box', locals: { movie: @new_movie } ) %>")

This is using jQuery to find the div with the id “movie-X” and replace the html inside of it with the partial “movie_media_box” passing it “@new_movie” instead of the previous movie being used.

And thats it, you now have a basic ajax request working for partial renders for Ruby On Rails!

I referred to: https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy to get my first understanding on how to do this.