问题
I'm using Rails 4 and I want to get a count of votes for each individual post review for a given post.
Schema:
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.
回答1:
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...
In your Post model:
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
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.
回答2:
Couple of issues I see:
PostReview.where(post_id: post.id)
can return more than one record.
Your relationship should be defined as post_review_votes
, so you'd want to call .post_review_votes
rather than PostReviewvotes
You might want one of the following:
`PostReview.where(post_id: post.id).first.post_review_votes.size
- If you only expect one PostReview this is probably what you want.
PostReview.where(post_id: post.id).collect{|pr| pr.post_review_votes.size}.sum
- This will take all of the post reviews, get the size of their votes, and add them together.
Or pure SQL:
PostReviewVotes.includes(:post_review).where("post_reviews.post_id: ?", post.id).count
来源:https://stackoverflow.com/questions/21472347/getting-count-by-drilling-down-through-relations