我有两个简单的模型,Pin 和 Comment,Comments 属于 Pin:
class Pin < ActiveRecord::Base
has_many :comments, dependent: :destroy
和
class Comment < ActiveRecord::Base
belongs_to :pin
在 Pin 的索引操作中,我基本上有一个所有引脚的列表 + 一个 div。当用户选择引脚时,此 div 必须显示所有注释。
概念很简单,但我不知道如何实现它。我发现许多主题都是相关的,但我总是迷失在与问题的差异中。
一些精确的问题:
- 如何做这个 ajax 加载?(与jquery)
- 我是否需要使用部分或使用注释的索引视图?
我将使用一个链接让用户选择一个 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
<div id="comments_div">
<% comments.each do |c| %>
<p>
<h1><%= c.title %></h1>
<h6>by <%= c.author %> </h6>
<%= c.content %>
</p>
<% end %>
</div>
希望对您有所帮助!