3

对大多数人来说可能是一个简单的问题,但仍然要掌握数据库查询。我有可以评分的食谱,我现在想收集这些评分并获得平均评分。一个菜谱有很多评分(我认为这是正确的关系)

我已经创建了一个这样的范围

class Recipe < ActiveRecord::Base
belongs_to :user
has_many :ratings
attr_accessible :country, :description, :name
scope :average_rating,includes(:ratings).group('recipe_id').where('AVG(ratings.rating)');
end

评级模型

class Rating < ActiveRecord::Base
has_many :users
attr_accessible :ratings, :recipe_id, :user_id
end 

我的评分是否也应该包括 has_many :recipes ?

在我的控制器中,我创建了一个实例变量来显示结果

@avgrating = Recipe.average_rating

但坚持如何让它在我的视图中显示在这个块中,例如在我的索引中,控制器只是

 @recipes = Recipe.all

和视图

<% @recipes.each do |recipe| %>
<tr>
<td><%= recipe.name %></td>
<td><%= recipe.description %></td>
<td><%= recipe.country %></td>
<td>Avg Rating =<%= not sure here %></td>
</td>
</tr>
<% end %>

当我看到答案时,我肯定会感到很傻,但现在想不出该怎么做

谢谢

4

2 回答 2

7

尝试<td>Avg Rating =<%= recipe.ratings.average(:ratings) %></td>

于 2013-02-21T14:20:17.133 回答
1

试试这个:

  recipe.ratings.average(:ratings)

或者

  <% ratings = recipe.ratings %>
  <%= ratings.map(&:ratings).sum/ratings.count %>
于 2013-02-21T14:20:55.123 回答