0

我有以下型号:

产品:

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),并且我的推荐控制器中有一个操作,它更新 RecommendationsRatings 连接表以将评级与推荐相关联。谢谢!

4

1 回答 1

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 / float 存储等级

于 2013-02-07T20:12:56.167 回答