views:

42

answers:

1
+1  Q: 

Find by Quantity

Let's say I have a model

Vehicle

and it

has_many :wheels

What is the correct find / :conditions => ... statement to find only vehicles with 3 or more wheels, e.g. tricycles, cars, trucks, tanks etc...?

+3  A: 

Not the same, but I believe you can solve your Problem with the help of the answers to this question: http://stackoverflow.com/questions/2900031/using-named-scope-with-counts-of-child-models

In Short:

Add wheels_count column to your vehicle table

class Wheel < ActiveRecord::Base
  belongs_to :vehicle, :counter_cache => true # this will autoupdate the wheels_count on Vehicle
end

Now you can search your Vehicle by the count of Wheels:

# for all Vehicles with 4 Wheels
Vehicle.all(:condition => { :wheels_count => 4 })
# or for all Vehicles with more than 3 Wheels
Vehicle.all(:condition => ["wheels_count > ?", 3])

Update:

class AddWheelCount < ActiveRecord::Migration
  def self.up  
    add_column :vehicles, :wheels_count, :integer, :default => 0  

    Vehicle.reset_column_information  
    Vehicle.all.each do |p|  
      p.update_attribute :wheels_count, p.wheels.length  
    end  
  end  

  def self.down  
    remove_column :vehicles, :wheels_count  
  end
end

So the wheels_count is set to the current count

jigfox
ah i see. this looks good. i hope adding the :counter_cache this late in (millions of records) will still work.
scrrr
I've updated my answer with the migration, so it should work with millions of already existing records.
jigfox
excellent, thank you!
scrrr