Filip Maryniak Filip Maryniak - 1 year ago 111
Ruby Question

RUBY ON RAILS 4.2.3 Calculate average

I'm junior RoR programmer.
I know that Ruby language has a calculate method, When I type this in rails console:

,it calculates the average value from field
. It works, but how to add average value to the view?

I have a Items catalogue. Every item has a Review which include rating (integer).

How to display on the view (i.e. show.html.erb) the average value from all rating fields in Review model?

Answer Source


first step: Add to your model controller, to def show: @rating = Model.where(:model_id => params[:id]).average(:attribute).to_i

second step: add to your model view to show.html.erb: <%= @rating %>

model_id = your model, i.e. Post will be :post_id :attribute = your attribute, i.e. :rating

It's all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download