Probably a simple question for most, but still getting to grips with Database queries. I have recipes that can be given a rating, I now want to collect those ratings and get the average rating. A recipe has many ratings (I think this is the correct relationship)
I have created a scope like so
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
ratings model
class Rating < ActiveRecord::Base
has_many :users
attr_accessible :ratings, :recipe_id, :user_id
end
Should my ratings also include has_many :recipes ?
In my controller i have created an instance variable to display the result
@avgrating = Recipe.average_rating
but stuck on how to get this to show in my view within this block for example within my index which the controller is simply
@recipes = Recipe.all
and the view
<% @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 %>
Im sure ill feel silly when i see the answer but just cant think how to do it right now
Thanks
try <td>Avg Rating =<%= recipe.ratings.average(:ratings) %></td>