我有两个简单的模型,Pin 和 Comment,Comments 属于 Pin:
class Pin < ActiveRecord::Base
has_many :comments, dependent: :destroy
和
class Comment < ActiveRecord::Base
belongs_to :pin
在 Pin 的索引操作中,我基本上有一个所有 Pin 的列表 + 一个 div。 当用户选择图钉时,此 div 必须显示所有评论。
概念很简单,但我不知道如何实现它。 我发现了许多相关的主题,但我总是迷失在与我的问题的差异中。
一些具体问题:
- 如何进行ajax加载? (使用jquery)
- 我需要使用部分内容还是使用评论索引 View ?
最佳答案
我将使用一个链接让用户选择一个 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
在这种情况下, Controller 将寻找渲染 pin_comments.js.erb,它将与您的评论 div 交互。
//pin_comments.js.erb
$("#comments_div").html("<%= j(render('show_comments', :comments=> @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>
希望有帮助!
关于jquery - Rails 3 - 使用 Ajax 和 jquery 更新 div 内容(嵌套资源),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13470953/