Ric*_*wis 3 ruby-on-rails scopes ruby-on-rails-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
Run Code Online (Sandbox Code Playgroud)
评级模型
class Rating < ActiveRecord::Base
has_many :users
attr_accessible :ratings, :recipe_id, :user_id
end
Run Code Online (Sandbox Code Playgroud)
我的评级还应包括has_many:食谱吗?
在我的控制器中,我创建了一个实例变量来显示结果
@avgrating = Recipe.average_rating
Run Code Online (Sandbox Code Playgroud)
但坚持如何让这个在我的视图中显示在这个块中,例如在我的索引中,控制器很简单
@recipes = Recipe.all
Run Code Online (Sandbox Code Playgroud)
和观点
<% @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 %>
Run Code Online (Sandbox Code Playgroud)
当我看到答案时,我肯定感到愚蠢,但是现在无法想到如何做到这一点
谢谢