Rails 3 – 使用Ajax和jquery(嵌套资源)更新div内容
我有两个简单的模型,Pin和Comment,评论属于Pin:
class Pin < ActiveRecord::Base has_many :comments, dependent: :destroy
和
class Comment < ActiveRecord::Base belongs_to :pin
在Pin I的索引动作中,基本上是所有引脚+ div的列表。 当用户选择一个引脚时,该div必须显示所有注释。
概念很简单,但我无法弄清楚如何实现它。 我发现很多相关的主题,但我总是迷失在与我的问题的差异。
一些确切的问题:
- 怎么做这个ajax加载? (用jquery)
- 我是否需要使用partials或使用注释的索引视图?
我将使用一个链接供用户选择Pin但你明白了:
#:remote => true allows ajax stuffz. <%= link_to 'show comments', pin_comments_path(@pin), :remote=> true %>
在comments_controller.rb中(我在这里使用索引操作,但根据您的需要调整)
def index @pin = Pin.find(params[:pin_id]) @comments = @pin.comments.all respond_to do |format| format.js { render :pin_comments } end end
在这种情况下,控制器将寻找渲染pin_comments.js.erb,它将与您的注释div进行交互。
//pin_comments.js.erb $("#comments_div").html("<%= j(render('show_comments', :comments=> @comments)) %>");
查看部分模板以显示评论
#_show_comments.html.erb
希望有所帮助!
<%= c.title %>
by <%= c.author %>
<%= c.content %> <% end %>