ruby on rails - ActiveRecord attribute depends of a calculation of other model -


this scenario:

class user < activerecord::base   has_many :things   # attr_accessible :average_rating end  class thing < activerecord::base   belongs_to :user     has_one :thing_rating end  class thingrating < activerecord::base   belongs_to :thing    attr_accessible :rating end 

i want have attribute in user model has average calculation of related thingsrating.

what best practice manage this?

thanks

the easy way :

class user < activerecord::base   has_many :things    def avg_rating     @avg_rating ||= average(things.map(&:thing_rating))   end    private   def average(values)     values.inject(0.0) { |sum, el| sum + el } / arr.size   end end 

this fine starter. if have bit of trafic, might find scaling problems.

you'll have refactor avoid making sql query things every time call method different user.
have several possibilites :

  • add field in user database, avg_rating, updated thingrating when it's created or updated.
  • use memcached or redis database cache value , invalidate cache every time thingrating updated or created.

these solutions aren't exhaustive of course. , find other ones better fit needs.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -