Search code examples
ruby-on-railsrating

Rails 4 Rating Inside Model


I'm quite new to Rails and was wondering what option would be best with a system of rating for users:

user has_many reviews

Each review contains a rating.

In order to display reviews count and average rating, is it a better idea to add these columns to the user model and update them through after_save callbacks on the review model or simply define functions that will use COUNT and AVERAGE, but will hit the DB everytime?


Solution

  • Definitely better to add columns, especially if you're sorting on them or showing them in a list.

    Agreed with the column definitions by @Halogen

    I tend to put these in methods on after_save to make sure all objects are validly saved first.

    after_save :set_reviews_average, set_reviews_count
    
    # Note: update_column won't trigger callbacks
    
    def set_reviews_average
      update_column(:reviews_average, reviews.average(:rating)) 
    end
    
    def set_reviews_count
      update_column(:reviews_count, reviews.count) 
    end