0

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?

muichkine
  • 2,890
  • 2
  • 26
  • 36
  • 1
    you can use `:includes` to get the correct number but that would be slower. – jvnill Feb 05 '13 at 13:14
  • Compared to overriding the `<=>` operator and using the `.uniq`? What would you advise? – muichkine Feb 05 '13 at 13:16
  • 1
    try the answer to this question http://stackoverflow.com/questions/14679793/query-that-joins-child-model-results-item-erroneously-shown-multiple-times – jvnill Feb 05 '13 at 13:21

0 Answers0