Rails has_many 使用 ActiveRecord 求和和计数

Rails has_many sums and counts with ActiveRecord

我进退两难,我想我可能把自己逼到了一个角落。这是设置。

我的网站有用户。每个用户都有他们 post 的故事集。每个故事都有其他用户的评论集。

我想在用户页面上显示其他用户的评论总数。

所以一个用户 has_many 个故事和一个故事 has_many 评论。

我尝试的是在@stories 中加载所有用户故事,然后显示@stories.comments.count,但是当我尝试这样做时,我得到了未定义的方法'comments'。有没有一种有效的 ActiveRecord 方法可以做到这一点?

在你的控制器中你应该有这样的东西(注意 includes 的使用):

@user = User.find( params[:id] )
@stories = @user.stories.includes(:comments)

然后在您的视图中,您可以执行类似以下操作来显示该特定用户的评论总数:

Total number of comments: <%= @stories.map{|story| story.comments.length}.sum %>
class User < ActiveRecord::Base
  has_many :stories
  has_many :comments, through: :stories
end

class Story < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :story
end

现在你应该可以得到User.last.comments.count

我认为您需要进一步完善它以获得正确的标签。

快速解决方案是遍历@stories 集合并将计数相加。这不是一个纯粹的活动记录解决方案。

totalComments = 0
@stories.each do |story|
    totalComments += story.count
end

对于纯活动记录解决方案,我需要假设每个 has_many 关联都有对应的 belongs_to 关联。所以一个用户 has_many 故事和一个故事 belongs_to 一个用户。如果是这种情况并且评论与故事有类似的关联,那么您可以按 user_id 搜索评论。类似于:

Comments.where("comment.story.user" => "userId")

希望对您有所帮助。