【发布时间】:2013-02-06 21:49:13
【问题描述】:
对于大多数人来说可能是一个简单的问题,但仍然要掌握数据库查询。我有可以评分的食谱,我现在想收集这些评分并获得平均评分。一个菜谱有很多评分(我认为这是正确的关系)
我已经创建了一个这样的范围
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 %>
当我看到答案时我肯定觉得很傻,但现在想不出该怎么做
谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 scopes