There are multiple ways of doing this. Easiest way is exposing it as a state on the controller, which is the @average
, which can then be accessed in the view. As easy as it might be, I don't recommend this approach.
What I do recommend is, adding a method on your model,
model_instance#review_ average
and when you are exposing (using the @model_instance
) the instance of the model in the #show
action of your controller to the view, you can just call @model_instance.review_average
What is the advantage of the second approach? It hides the logic from the view and controller, and pushes it into the model, which in turn makes it easier to write an automated test case.
for implementing average, check: How do I create an average from a Ruby array?
I'm also guessing that you have a has-many relation. It should not be too difficult to do the above.
One thing that you have to also keep an eye for, is n+1 queries, But this becomes an issue only when you have to show the avg in the index page.