【问题标题】:Get the average rating for each object获取每个对象的平均评分
【发布时间】: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


    【解决方案1】:

    试试这个:

      recipe.ratings.average(:ratings)
    

      <% ratings = recipe.ratings %>
      <%= ratings.map(&:ratings).sum/ratings.count %>
    

    【讨论】:

      【解决方案2】:

      试试&lt;td&gt;Avg Rating =&lt;%= recipe.ratings.average(:ratings) %&gt;&lt;/td&gt;

      【讨论】:

      • 那么这里不需要范围吗?把事情复杂化了?现在获取未定义的方法平均值
      • 是的,不需要范围。那应该是average,而不是avg。对不起!
      • 是的,很棒,工作,我假设我现在可以添加到这个并向上或向下舍入数字,因为目前得到像 4.2 这样的结果
      • 是的。只需附加 .round(2).ceil.floor
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 2016-03-28
      相关资源
      最近更新 更多