我有以下模型:recommendations
、ratings
和 product
。一个product
has_many
recommendations
,一个recommendation
has_many
products
,一个recommendation
has_many
ratings
和一个rating
belongs_to
一个recommendation
。
我目前正在使用以下查询来查找索引中的所有记录:
@recommendations = Recommendation.find(:all, :joins => :products, :conditions => ["product_id = ? AND rating_set = ?", (params["product_id"]), (params["rating_set_id"])])
为了获得每条记录的推荐评级,我在我的观点中调用了另一个范围。
如何设置 @recommendatons
以获取特定 product_id
和 rating_set
找到的所有推荐和评级?
我试过:
Recommendation.find(:all, :joins => :products,:include => :ratings, :conditions => ["product_id = ? AND rating_set = ?",2086981,40]).each do |rec|
puts rec.rating
end
打印了 Nil
。
模型更新:
产品
class Product < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :recommendations, :through => :product_recommendations
end
推荐
class Recommendation < ActiveRecord::Base
has_many :product_recommendations, :dependent => :destroy
has_many :products, :through => :product_recommendations
has_many :ratings
end
评分:
class Rating < ActiveRecord::Base
belongs_to :recommendation
end
这是我需要的结果(这只有在评分已经创建的情况下才有效,这就是我不能使用它的原因):
@recommendations = Rating.find(:all, :conditions => ["product_id = ? AND rating_set = ?", (params["product_id"]), (params["rating_set_id"])])
我在查询什么: 我需要找到所有推荐,其中 product_id 和 rating_set = ?, ?鉴于此,找到属于每个建议的所有评级。
更新
我能够使用以下查询取回属于推荐的所有评级:
Recommendation.joins(:product_recommendations).includes(:ratings).where(:product_recommendations => { :rating_set => 48, :product_id => 2144877 })
当我遍历返回的评级数组时,它们没有限定在正确的 rating_set 范围内,而是我获得了属于特定推荐的所有 rating_sets 的所有评级。我怎样才能为每个推荐和 rating_set 取回一组评分。
最佳答案
您的数据模型真的如您所描述的那样吗?您最初的描述似乎表明这都是父->子(一对多)关系。产品与推荐具有一对多关系,推荐与评级具有一对多
这意味着像这样的表结构:
products table
:id
recommendations table
:id
:product_id
ratings table
:id
:recommendation_id
但是,您发布的所有生成的 SQL 查询似乎都显示了某种名为 product_recommendations
的连接表。那是什么?
您是否真的使用名为 product_recommendations
的连接表在产品和推荐之间建立多对多关系?
如果是这样,我会说您的查询应该有效,但您需要通过将字段定义为 has_many
和 belongs_to
而不是 has_and_belongs_to_many
用于产品和推荐模型。
看看这是否有帮助 http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association
关于ruby-on-rails - 具有 has_many 关联的 Rails 3 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15350735/