我有两个简单的模型,Pin 和 Comment,Comments 属于 Pin:
class Pin < ActiveRecord::Base
has_many :comments, dependent: :destroy
and
class Comment < ActiveRecord::Base
belongs_to :pin
在 Pin 的索引操作中,我基本上有一个所有引脚的列表 +div.
This div当用户选择 pin 时必须显示所有评论。
概念很简单,但我不知道如何实现它。
我发现了许多相关的主题,但我总是迷失在与我的问题的差异中。
一些具体的问题:
- 如何进行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>
希望有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)