2

我在编写范围以返回所有 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)
}

这不起作用,因为它会找到至少一个列表不在问题中的任何产品。我需要某种方式来询问在特定问题中没有列表的所有产品。

4

1 回答 1

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
于 2013-01-29T21:46:51.020 回答