I have this configuration:
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
Now, here is the worry,
Inventory.find(2).boxes.count
>> 140
while
Box.for_inventory(2).count
>> 506
Box.for_inventory(2).uniq.count
>> 506
The thing is that if a Box
contains multiple Toys
, it is returned several times.
So, I thought I could override the <=>
operator for the Box
class so .uniq
would actually do something and redduce the list from 506 to 140. But isn't there a better way to change the Box::for_inventory
scope so it does that at request time?