我在编写范围时遇到问题,以返回所有has_many关联符合条件的记录。
我有这些模特:
class Product
has_many :listings
end
class Listing
belongs_to :product
belongs_to :issue
end
class Issue
has_many :listings
end
基本上,产品可以列在几个不同的问题中。我希望能够获得在特定问题中没有列表的所有产品。到目前为止,我的产品型号中有这个范围:
scope :not_listed_in, lambda { |issue|
joins(:listings)
.where("listings.issue_id != ?", issue.id)
}
这不起作用,因为它会找到任何至少有一个列表不在问题中的产品。我需要一些方法来询问所有在特定问题中没有列表的产品。
答案 0 :(得分:2)
假设您正在使用ActiveRecord,您可以通过查找所有产品并删除问题中的产品来实现此目的。这通常会产生一个数组,所以在下面的代码中,我做了一个额外的数据库查询,让它返回一个作用域结果,这样你就可以将其他“where”子句级联到结果中。
class Product < ActiveRecord::Base
has_many :listings
scope :not_listed_in, lambda { |issue|
id_list = Product.pluck(:id) - issue.products.pluck(:id)
Product.where(id:id_list)
}
end
class Listing < ActiveRecord::Base
belongs_to :product
belongs_to :issue
end
class Issue < ActiveRecord::Base
has_many :listings
has_many :products, through: :listings
end