【问题标题】:Getting count by drilling down through relations通过关系向下钻取计数
【发布时间】:2014-01-31 04:21:55
【问题描述】:

我正在使用 Rails 4,我想对给定帖子的每个单独的帖子评论进行投票计数。

架构:

Post    PostReview    PostReviewVote
id      post_id       post_review_id
        user_id       user_id
                      voted_on_date

我有类似的东西:

table.table.table-striped.table-hover
  thead
    tr
      th Post Name
      th Reviews Created For Post
      th Total Votes in All Reviews For Post
  tbody
    - for post in @posts
      tr
        td= post.name
        td= PostReview.where(post_id: post.id).size
        td= PostReview.where(post_id: post.id).PostReviewVotes.size

但它没有获取,引用运行时错误:

undefined method `PostReviewVotes' for #<ActiveRecord::Relation []>

有什么建议吗?我的模型有正确的关联,仅供参考。

【问题讨论】:

  • 你说他们有适当的关联。 Post 是否有关联:has_many :PostReviewVotes, through: PostReview

标签: ruby-on-rails ruby activerecord ruby-on-rails-4 where


【解决方案1】:

你可以这样做:

post.post_reviews.count
post.post_review_votes.count

如果你按照你说的定义了所有的关联。

或者如果你想要一个方法......

在您的 Post 模型中:

def post_votes_total
  self.post_review_votes.count
end

只要你在Post中定义了关系:

has_many :post_review_votes, through: :post_reviews

由于您将@posts 变量传递给视图:

post.post_votes_total

在视图中使用内置的关联方法很好,但如果逻辑变得更复杂,您应该使用模型方法或辅助方法。

【讨论】:

    【解决方案2】:

    我看到的几个问题:

    PostReview.where(post_id: post.id) 可以返回多条记录。

    你的关系应该定义为post_review_votes,所以你应该调用.post_review_votes而不是PostReviewvotes

    您可能需要以下之一: `PostReview.where(post_id: post.id).first.post_review_votes.size- 如果您只期望一个 PostReview,这可能就是您想要的。

    PostReview.where(post_id: post.id).collect{|pr| pr.post_review_votes.size}.sum - 这将获取所有帖子评论,获取他们的投票大小,并将它们加在一起。

    或者纯SQL:

    PostReviewVotes.includes(:post_review).where("post_reviews.post_id: ?", post.id).count

    【讨论】:

    • 我认为他希望在该列中计算PostReview.where(post_id: post.id),这就是为什么他要计算它返回的数字。
    • @Beartech:没错。至于.collect{},这真的是最好的方法吗?看起来很复杂。
    • @Serg 可能有一个 ActiveRecord 查询可以更干净地生成这个总和。
    • 我认为你可以加入。但我认为你不应该在视图中做那种逻辑。您应该在模型或助手中创建一些辅助方法。这样您就可以在视图中调用该方法。
    • 另外,我认为您需要再喝一杯 GeekOnCoffee,他使用的是“投票”而不是“笔记”。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2011-01-21
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多