upto 2.14, added rating average counting for breweries

This commit is contained in:
Aaro Koivukangas
2023-08-08 11:08:38 +03:00
parent d6a1de554d
commit 80e1c6407d
2 changed files with 37 additions and 0 deletions
+27
View File
@@ -1,5 +1,6 @@
class Brewery < ApplicationRecord
has_many :beers, dependent: :destroy
has_many :ratings, through: :beers
def print_report
puts name
@@ -11,4 +12,30 @@ class Brewery < ApplicationRecord
self.year = 2023
puts "changed year to #{2023}"
end
def average_rating
total_score = 0
count = self.count_ratings
if count == 0
return 0
end
self.beers.each do |beer|
beer.ratings.each do |rating|
total_score += rating.score
end
end
return total_score / count
"This brewery has #{count} #{pluralize count, "rating"} with an average of #{average}"
end
def count_ratings
count = 0
self.beers.each do |beer|
count += beer.ratings.count
end
return count
end
end
+10
View File
@@ -14,6 +14,16 @@
<%= brewery.beers.count %>
</p>
<% if brewery.count_ratings != 0 %>
<p>
This brewery has <% brewery.count_ratings %> <%= pluralize brewery.count_ratings, "rating" %> with an average of <%= brewery.average_rating%>
</p>
<% else %>
<p>
This brewery has no ratings
</p>
<% end %>
<p>
<% brewery.beers.each do |beer| %>
<%= link_to beer.name, beer %>