我使用的是Rails 3.0。我有两个表: Listings和Offers。has-many提供的列表。优惠的accepted可以是true或false。
我想选择没有accepted为真的报价的每个列表。我试过了
Listing.joins(:offers).where('offers.accepted' => false)但是,由于一个列表可以有多个报价,这将选择包含未接受报价的每个列表,即使该列表有一个已接受的报价也是如此。
如果这还不清楚,我想要的是集合的补码:
Listing.joins(:offers).where('offers.accepted' => true)我目前的临时解决方案是获取所有它们,然后对数组进行过滤,如下所示:
class Listing < ActiveRecord::Base
...
def self.open
Listing.all.find_all {|l| l.open? }
end
def open?
!offers.exists?(:accepted => true)
end
end我更希望解决方案在数据库端运行过滤。
发布于 2011-08-21 00:01:48
我想到的第一件事就是在数据库中做你现在正在做的事情。
scope :accepted, lambda {
joins(:offers).where('offers.accepted' => true)
}
scope :open, lambda {
# take your accepted scope, but just use it to get at the "accepted" ids
relation = accepted.select("listings.id")
# then use select values to get at those initial ids
ids = connection.select_values(relation.to_sql)
# exclude the "accepted" records, or return an unchanged scope if there are none
ids.empty? ? scoped : where(arel_table[:id].not_in(ids))
}我确信这可以使用外部连接和分组更干净地完成,但我不会立即意识到这一点:-)
https://stackoverflow.com/questions/7132355
复制相似问题