2012-11-04 3 views
0

좋아요, 그래서 저는 서평 검토 사이트에서 일하고 있습니다. 나는 certian 저자가 모든 책의 평균 등급을 보여주고 싶습니다. 이것은 내가 현재 가지고있는 것이지만 작동하지만 더 좋은 방법이 있어야합니다.활성 레코드의 활성 레코드 평균

<% @author.books.each { |book| book.reviews.each { |review| x = x + review}} %>
<% @author.books.each { |book| book.reviews.each { |review| y = y +1}} %>
<%= x/y %>

나는 <% @book.reviews.average(:ratings) %>

을하지만

<% @author.books.reviews.average(:ratings) %>

은 안타깝게도 위의 명령이 수행 비슷한 일하는 것이 더 우아한 옵션이 있어야한다 수에도 작동하지 않습니다.<% @author.books.count %> 않습니다.

루비 1.9.2p290 및 레일 사용 3.2.8 제공 할 수있는 도움에 감사드립니다.

수정 첫 번째 대답 후에 내 업데이트 된 클래스 파일 추가.
author.rb

class Author < ActiveRecord::Base
attr_accessible :a1stname, :asurname
has_many :books
has_many :reviews :through => :books
def afull_name
"#{asurname}, #{a1stname}"
end
end

book.rb 내가 @author 전화를 걸거나 Author.find 때

class Book < ActiveRecord::Base
attr_accessible :author_id, :description, :title
belongs_to :author
has_many :reviews
validates :author_id, presence: true
end

는 지금은

를 얻을 수
syntax error, unexpected ":", expecting keyword_end 
      has_many :reviews :through => :books 
          ^ 
+0

시도 .joins으로 사용하지만, 정의되지 않은 메서드 '조인'을 –

답변

1

의 관계는

author has_many :books 
book has_many :reviews 

author.reviews.average(:ratings) 
+0

예상치 못한 가지고 할 수

author has_many :reviews :through => :books #uses a inner join 

를 추가 할 경우 ':' , expecting keyword_end has_many : reviews : * through => : books –

+0

이것은 정확히 내가 본 것처럼 보입니다. d하지만 작동하지 않습니다 :에 대한 설명을 여러 번 읽었습니다. 제대로 쓰여졌습니다. 내 모델 파일을 원래 질문에 게시했습니다. –

+0

나는 바보 야! for : the : after 리뷰 답을 적절히 업데이트하십시오. 고맙습니다. –