jeudi 19 février 2015

ActiveRecord: How to order by weighted average of associated through model?

I have 3 models,



#user.rb
class User < ActiveRecord::Base
has_many :pictures
has_many :ratings, dependent: :destroy
has_many :rated_pictures, through: :ratings, source: :picture
end

#picture.rb
class Picture < ActiveRecord::Base
#id, image, :user_id
has_many :ratings, dependent: :destroy
has_many :rated_users, through: :ratings, source: :user

def weighted_average
data = ratings.group("stars").count
w_sum = 0
data.each{ |key, value| w_sum += key * value }
(w_sum.to_f/data.values.sum).round(2)
end
end

#rating.rb
class Rating < ActiveRecord::Base
#id, user_id, picture_id and stars
belongs_to :user
belongs_to :picture
end


User can rate other user's picture out of 5, I am calculating average(weighted average) of a picture using the function picture.weighted_average.



# To can get a user's pictures
user = User.find_by_email 'abc@sample.com'
pictures = user.pictures


My query is how to order a user pictures by weighted_average using ActiveRecord?


Aucun commentaire:

Enregistrer un commentaire