获取计数钻上下贯通的关系 [英] Getting count by drilling down through relations
问题描述
我用Rails 4,我希望得到选票的计数为每个岗位审查特定职位。
I'm using Rails 4 and I want to get a count of votes for each individual post review for a given post.
模式:
Post PostReview PostReviewVote
id post_id post_review_id
user_id user_id
voted_on_date
我是这样的:
I have something like:
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
但它不是获取,理由是运行时错误:
But it's not fetching, citing a runtime error:
undefined method `PostReviewVotes' for #<ActiveRecord::Relation []>
有什么建议?我的模型有适当的关联,仅供参考。
Any suggestions? My models have the proper associations, FYI.
推荐答案
您可以简单地做到这一点:
You could simply do this:
post.post_reviews.count
post.post_review_votes.count
如果你把所有的关联定义就像你说的。
If you have all the associations defined as you say.
如果你想有一个方法吧...
or if you want a method for it...
在您的Post模型:
def post_votes_total
self.post_review_votes.count
end
只要你定义在帖子的关系:
As long as you have defined the relationship in Post:
has_many :post_review_votes, through: :post_reviews
由于要传递@posts变量的观点:
Since you are passing the @posts variable to the view :
post.post_votes_total
使用内置在意见关联方法是好的,但如果逻辑变得更加复杂,你应该使用一个模型方法或一个辅助方法。
Using the built in association methods in the views is fine, but if logic gets more complicated you should really use a model method or a helper method.
这篇关于获取计数钻上下贯通的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!