1

I have created a loop, to calculate a total rating of a record. To do this I am first looping through all the child records (ratings), extracting the rating from each row, adding it to the total and then outputting the total.

<% total = 0 %>
<% for ratings in @post.ratings %>
    <% total = (total + ratings.rating) %>
<% end %>
<%= total %>

My question is, simply, Is this the rails way?

It achieves the desired result, although needs 5 lines to do so. I am worried I am bring old habits from other languages into my rails project, and I am hoping someone could clarify if there is an easier way.

3 Answers 3

3

The following, preferably in the controller, will do it succinctly:

@rating = @post.ratings.sum { &:rating }

If that seems cryptic, you might prefer

@rating = @post.ratings.inject(0) { |sum, p| sum + p.rating }

Note, however, that this will fail if any of the ratings are null, so you might want:

@rating = @post.ratings.inject(0) { |sum, p| sum + (p.rating || 0) }
Sign up to request clarification or add additional context in comments.

1 Comment

You can convert rating to_i explicitly to avoid || operator. But anyway - the first example is the only one you should accept - it reduces count of db queries to 1 and increase performance.
1

You should generally keep logic out of your views. I would put that code in a helper or a controller, and the call a method to calculate the total

Comments

0

Put the following in your controller, then you just need to use @rating in your view:

total = 0
@rating = @post.ratings.each { |r| total += r.rating }

Or you could move it into the Post model and do something like:

def self.total_rating
  total = 0
  ratings.each { |r| total += r.rating }
  total
end

and then simply call @post.total_rating

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.