2014-01-31 3 views
1

나는 레일 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 []> 

어떤 제안? 내 모델에는 적절한 연관성이 있습니다 (FYI).

+0

그들은 적절한 연관성이 있다고합니다. 'Post'는'has_many : PostReviewVotes, through : PostReview'라는 연관성을 갖고 있습니까? – Beartech

답변

1

당신은 간단하게이 작업을 수행 할 수 있습니다 :

post.post_reviews.count 
post.post_review_votes.count 

당신이 말하는대로 정의 된 모든 연결을해야합니다.

또는 당신은 당신의 포스트 모델에서 그것을하는 방법 ...

을 원하는 경우 :만큼 당신이 포스트의 관계를 정의로

def post_votes_total 
    self.post_review_votes.count 
end 

을 :

has_many :post_review_votes, through: :post_reviews 

이후를 @posts 변수를 뷰에 전달하고 있습니다.

뷰에서 내장 된 연관 메서드를 사용하는 것은 좋지만, 논리가 더 복잡해지면 실제로 모델 메서드 또는 도우미 메서드를 사용해야합니다.

0

문제의 커플은 내가 참조 :

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

+1

나는 그 열에'PostReview.where (post_id : post.id) '의 수를 원한다고 생각합니다. 그래서 그가 반환하는 수에 대해 계산을하고 있습니다. – Beartech

+0

@Beartech : 맞습니다. '.collect {}'에 관해서는 이것을 실제로하는 가장 좋은 방법입니까? 뒤얽힌 것 같습니다. – sergserg

+0

@Serg이 합계를보다 명확하게 생성하는 ActiveRecord 쿼리가있을 수 있습니다. – GeekOnCoffee