我有以下型号:
产品:
class Product < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :recommendations, :through => :product_recommendations
end
产品推荐:
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
推荐评级:
class RecommendationRating < ActiveRecord::Base
belongs_to :recommendation
belongs_to :rating
end
我如何计算给定推荐的平均评分?我的评级表只包含4条记录(评级1-4),我的推荐控制器中有一个操作,它会更新推荐评级联接表,将评级与推荐关联起来。谢谢
您尝试过吗:
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/foat,它存储评级