0

我有这个配置:

model Box < ActiveRecord::Base
  has_many :toys
  has_many :inventories, :through => :toys

  scope :for_inventory, lambda{ |inv| joins(:toys).where("toys.inventory_id = ?",inv) }
end

model Toy < ActiveRecord::Base
  belongs_to :box
  belongs_to :inventory
end

model Inventory < ActiveRecord::Base
  has_many :toys
  has_many :boxes, :through => :toys
end

现在,担心的是,

Inventory.find(2).boxes.count
>> 140

尽管

Box.for_inventory(2).count
>> 506
Box.for_inventory(2).uniq.count
>> 506

问题是,如果 aBox包含多个Toys,它会被多次返回。所以,我认为我可以覆盖该类的<=>运算符,因此实际上会做一些事情并将列表从 506 减少到 140。但是没有更好的方法来更改范围,以便在请求时执行此操作吗?Box.uniqBox::for_inventory

4

0 回答 0