Rails provides a very easy way to implement Ajax. I got a Service and a ServiceComment models and each service has many service_comments. I have a service_comment create form and a partial which shows all the service_comments of that viewing service in the app/views/services/show.html.erb. Everything works fine without Ajax. Now comes to the Rails magic.
1. This is the app/views/services/show.html.erb which contains the service_comment create form and the service_comments partial. nothing needs to change here.
app/views/services/show.html.erb
... <!-- service_comment create form --> <%= render 'service_comments/service_comment_form' %> <!-- service_comments partial --> <% unless @service_comments.empty? %> <%= render('service_comments/all_comments') %> <% end %> ...
2. Here are the partials being used
app/views/service_comments/_all_comments.html.erb
<table id="service-comments"> <tbody> <%= render @service_comments %> </tbody> </table>
app/views/service_comments/_service_comment.html.erb
<tr> <td><%= service_comment.text %></td> </tr>
3. Add :remote => true to the form_for function in the service_comment create form partial as follow
app/views/service_comments/_service_comment_form.html.erb
... <!--%= form_for @service_comment do |f| %--> <!-- add :remote => true to the form_for function --> <%= form_for @service_comment, :remote => true do |f| %> ...
3. Modify the app/controllers/service_comments_controller.rb
... def create @service = Service.find(params[:service_comment][:service_id]) @service_comment = current_user.service_comments.build(params[:service_comment]) if @service_comment.save # NO NEED TO SHOW THE FLASH MESSAGE AND REDIRECT #flash[:success] = "Service comment created" #redirect_to @service # Reload the service comments for rendering the updated result in create.js @service_comments = Service.find(params[:service_comment][:service_id]).service_comments end end ...
4. The last step is to create the app/views/service_comments/create.js.erb. This js file end in .erb which means that we can embed Ruby script inside. It is run after the server response to render the result on the view. In this example, the all_comments partial is re-rendered.
$("service-comments").update("<%= escape_javascript(render('service_comments/all_comments')) %>");
Your Ajax create form should work now. Check it out.
Done =)
Reference: