活动记录的活动记录的平均值

时间:2012-11-04 03:19:30

标签: ruby-on-rails

好的,我正在写一本书评网站。 我想显示一位证书作者对所有书籍的平均评分。这就是我目前的工作方式,但必须有更好的方法。

<% @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 %>确实如此。

使用Ruby 1.9.2p290和rails 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

  

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

现在,当我打电话给@author或Author.find时,我得到了

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

1 个答案:

答案 0 :(得分:1)

如果关系是

author has_many :books 
book has_many :reviews

添加

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

可以用作

author.reviews.average(:ratings)
相关问题