1

我正在尝试在 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 只给我一条评论?

提前致谢

4

2 回答 2

1

代替:

Comment.find_by_thought_id

尝试:

Comment.find_all_by_thought_id
于 2012-04-23T18:04:27.917 回答
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,它更快,因为它不是动态方法。

于 2012-04-23T18:24:45.640 回答