我有以下模特:
产品:
class Product < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :recommendations, :through => :product_recommendations
end
ProductRecommendation:
class ProductRecommendation < ActiveRecord::Base
belongs_to :recommendation
belongs_to :product
end
建议:
class Recommendation < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :products, :through => :product_recommendations
has_many :recommendation_ratings, :dependent => :destroy
has_many :ratings, :through => :recommendation_ratings
end
评分:
class Rating < ActiveRecord::Base
has_many :recommendation_ratings, :dependent => :destroy
has_many :recommendations, :through => :recommendation_ratings
end
RecommendationRating:
class RecommendationRating < ActiveRecord::Base
belongs_to :recommendation
belongs_to :rating
end
我如何计算给定建议的平均评分?我的评级表只包含4条记录,(评级1-4),我在推荐控制器中有一个操作,它更新了RecommendationsRatings连接表,将评级与推荐相关联。谢谢!
答案 0 :(得分:0)
你试过了吗?
class Product < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :recommendations, :through => :product_recommendations
has_many :ratings, :through => :recommendations
end
然后
p = Product.find 1
p.ratings.average(:rating)
这是假设Ratings模型有一个名为rating / int的int / float来存储评级