scrrr
scrrr

Reputation: 5340

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...?

Upvotes: 1

Views: 99

Answers (1)

jigfox
jigfox

Reputation: 18177

Not the same, but I believe you can solve your Problem with the help of the answers to this question: 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

Upvotes: 3

Related Questions