我有以下型号:
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
我试图通过以下方式选择product_id = recommendations
的所有x
:
RecommendationSet.joins(:products, :recommendations).where(product_id:1)
但是我收到了一个未知的列错误。如何加入选择给定product_id的所有建议。
Psudo代码:
查看recommendation_sets
product_id = ?
。查看recommendations
recommendation_set_id = ?
。
答案 0 :(得分:11)
你非常接近,在你的情况下这应该有效:
RecommendationSet.joins(:products, :recommendations).where(products: { id: 1 })
请记住,where子句中的必须在条件哈希中使用表名,而不是关系的名称。
作为一个例子,考虑这些关系:
User belongs_to :group
Group has_many :users
注意语法(复数/单数):
User.joins(:group).where(groups: { name: 'Admin' })
# ^ ^
Group.joins(:users).where(users: { id: 15 })
# ^ ^