我有以下型号:
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
我试图选择所有
recommendations
其中 product_id = x
, 通过做:RecommendationSet.joins(:products, :recommendations).where(product_id:1)
但是我收到一个未知的列错误。如何通过给定的 product_id 加入选择所有推荐。
伪代码:
查找
recommendation_sets
哪里product_id = ?
.查找 recommendations
哪里recommendation_set_id = ?
.
最佳答案
你很接近,在你的情况下 这应该有效:
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 })
# ^ ^
关于ruby-on-rails - Rails 多连接 AR 查询和 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18991957/