Peter Blomgren
Peter Blomgren

Reputation: 47

Average of an Active Record of an active record

Ok, So I'm working on a book review site. I am wanting to show the average rating of all the books by a certian author. This is what I have currently and it works but there has to be a better way.

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

I can do <% @book.reviews.average(:ratings) %>

but there has to be a more elegant option that would work similar to

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

Sadly the above command does not work even though <% @author.books.count %> does.

Using Ruby 1.9.2p290 and rails 3.2.8 Thank you so much for any help you can offer.

edited Adding my updated class files after first answer.
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

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

Now when I call @author or Author.find I get

syntax error, unexpected ":", expecting keyword_end
          has_many :reviews :through => :books 
                             ^  

Upvotes: 0

Views: 121

Answers (1)

Prasad Surase
Prasad Surase

Reputation: 6574

if the relationship is

author has_many :books 
book has_many :reviews

add

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

which can be used as

author.reviews.average(:ratings)

Upvotes: 1

Related Questions