如何使用jquery和partials在rails中呈现集合

时间:2012-04-23 18:01:44

标签: jquery ruby-on-rails collections partial-views render

我正在尝试在Rails 3.1上呈现一组评论,但只有关于该集合的第一条评论显示在网页上(评论与思想相关)。

首先,评论控制器:

def index
  @comments = Comment.find_by_thought_id(params[:thought_id])
  respond_to do |format|
    format.html
    format.js
  end
end

然后,查看index.js.erb

$("#thought_<%= params[:thought_id] %>").append("<%= escape_javascript(render'index') %>").effect("highlight", {}, 3000);

我正在渲染索引,现在是_index.html.erb

<div id="comments_<%= params[:thought_id] %>">
  <%= render @comments %>
</div>

最后是_comment.html.erb

<%= div_for comment do %>
  Posted <%=time_ago_in_words(comment.created_at)%> ago<br />
  <%= link_to 'Delete', comment_path(comment), :method => :delete, :class => "delete", :remote => true  %>
  <%= content_tag(:p, comment.description, :class => "comment-body") %>
<% end %>

为什么Rails只给我一个评论?

提前致谢

2 个答案:

答案 0 :(得分:1)

而不是:

Comment.find_by_thought_id

尝试:

Comment.find_all_by_thought_id

答案 1 :(得分:0)

1.9.3-head :035 > Tag.find_by_name('ruby')
  Tag Load (0.3ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'ruby' LIMIT 1
 => #<Tag id: 1231, name: "ruby", created_at: "2012-04-23 10:25:07", updated_at: "2012-04-23 10:25:07"> 
1.9.3-head :036 > Tag.where(:name => 'ruby')
  Tag Load (1.4ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'ruby'
 => [#<Tag id: 1231, name: "ruby", created_at: "2012-04-23 10:25:07", updated_at: "2012-04-23 10:25:07">, #<Tag id: 2420, name: "ruby", created_at: "2012-04-23 18:21:35", updated_at: "2012-04-23 18:21:35">]

当您执行 find_by_name 等动态查找器时,请注意 LIMIT 1

你最好使用 where ,它更快,因为它不是动态方法。