Rails 3 - Update div content with Ajax and jquery (nested resources)

亡梦爱人 提交于 2019-12-03 00:21:41

I'm going to use a link for the user to select a Pin but you get the idea:

#:remote => true allows ajax stuffz.
<%= link_to 'show comments', pin_comments_path(@pin), :remote=> true %>

In the comments_controller.rb (i'm using the index action here, but tweak to your needs)

def index 
  @pin = Pin.find(params[:pin_id])
  @comments = @pin.comments.all

  respond_to do |format|
    format.js { render :pin_comments }
  end
end

In this case the controller will look to render pin_comments.js.erb, which will interact with your comments div.

//pin_comments.js.erb
$("#comments_div").html("<%= j(render('show_comments', :comments=> @comments)) %>");

View partial template to show comments

#_show_comments.html.erb
<div id="comments_div">
    <% comments.each do |c| %> 
        <p>
           <h1><%= c.title %></h1>
           <h6>by <%= c.author %> </h6>
           <%= c.content %>
        </p>
    <% end %>
</div>

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!