所以我有一个帖子模型和投票模型,其中投票通过 post_id 与帖子相关联。
帖子模型
class Post < ActiveRecord::Base
attr_accessible :comment_count, :downvote, :id, :text, :title, :upvote, :url, :user_id, :users_voted_up_by, :users_voted_down_by
serialize :users_voted_up_by
serialize :users_voted_down_by
belongs_to :user
has_many :votes
end
投票模型
class Vote < ActiveRecord::Base
attr_accessible :direction, :post_id, :type, :voter_id
belongs_to :user
belongs_to :post
belongs_to :comment
end
我需要在数据库中查询 Votes
表中的所有行,这些行在我的循环中具有帖子的当前 post_id
:
<% @posts.each do |post| %>
<%= Vote.count(:post_id, params[:post_id]) %>
<% end %>
但这只是计算每一行,我可以写什么来关联它们?
最佳答案
推荐的方法是在查询中使用分组:
<% vote_counts = Vote.group(:post_id).
where(:post_id => @posts.map(&:id)).count %>
<% @posts.each do |post| %>
<%= post.id %>: <%= vote_counts[post.id] || 0 %>
<% end %>
分组查询的优点是它只访问数据库一次。如果您出于某些莫名其妙的原因希望对每个帖子进行单一计数,您可以简单地使用:
<% @posts.each do |post| %>
<%= post.id: %> <%= post.votes.count %>
<% end %>
不过,不要让第二种方法的简单性欺骗了您。这是自找麻烦,因为它涉及 N+1 模式。
关于mysql - Rails 计算列与 ID 匹配的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265850/