【问题标题】:Rails has_many sums and counts with ActiveRecordRails has_many 使用 ActiveRecord 求和和计数
【发布时间】:2015-12-30 04:31:00
【问题描述】:

我有一个两难境地,我想我可能已经把自己编码到了一个角落里。这是设置。

我的网站有用户。每个用户都有他们发布的故事集合。每个故事都有来自其他用户的 cmets 集合。

我想在用户页面上显示来自其他用户的cmets总数的计数。

所以一个用户有_many Stories,而一个Story has_many cmets。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:
    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

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

    【讨论】:

    • 这是一个很好的解决方案。
    【解决方案2】:

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

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

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

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

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

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

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

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

      Total number of comments: <%= @stories.map{|story| story.comments.length}.sum %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多