Rails多个连接AR查询和where子句

Yog*_*zzz 3 activerecord ruby-on-rails ruby-on-rails-3

我有以下型号:

class Product < ActiveRecord::Base
  has_many :product_recommendation_sets, :dependent => :destroy
  has_many :recommendation_sets, :through => :product_recommendation_sets
end

class ProductRecommendationSet < ActiveRecord::Base
  belongs_to :product
  belongs_to :recommendation_set
end

class RecommendationSet < ActiveRecord::Base  
  has_many :product_recommendation_sets, :dependent => :destroy
  has_many :products, :through => :product_recommendation_sets

  has_many :recommendation_recommendation_sets, :dependent => :destroy
  has_many :recommendations, :through => :recommendation_recommendation_sets
end

class RecommendationRecommendationSet < ActiveRecord::Base
  belongs_to :recommendation
  belongs_to :recommendation_set
end

class Recommendation < ActiveRecord::Base
   has_many :recommendation_recommendation_sets, :dependent => :destroy
   has_many :recommendations, :through => :recommendation_recommendation_sets
end
Run Code Online (Sandbox Code Playgroud)

我试图选择所有recommendationsproduct_id = x,通过这样做:

RecommendationSet.joins(:products, :recommendations).where(product_id:1)
Run Code Online (Sandbox Code Playgroud)

但是我得到一个未知的列错误.如何加入选择给定product_id的所有建议.Psudo代码:找到recommendation_sets哪里product_id = ?.找到recommendations哪里recommendation_set_id = ?.

MrY*_*iji 11

你非常接近,在你的情况下这应该工作:

RecommendationSet.joins(:products, :recommendations).where(products: { id: 1 })
Run Code Online (Sandbox Code Playgroud)

请记住,在where子句中,您必须在条件哈希中使用表的名称,而不是关系的名称.

作为示例,请考虑以下关系:

User belongs_to :group
Group has_many :users
Run Code Online (Sandbox Code Playgroud)

注意语法(复数/单数):

User.joins(:group).where(groups: { name: 'Admin' })
#               ^             ^
Group.joins(:users).where(users: { id: 15 })
#                ^            ^
Run Code Online (Sandbox Code Playgroud)