Ann
Ann

Reputation: 139

how to write active record query for selecting certain values in a column

I have a dogs table which has age as an attribute. Dogs with ages between 1 year -12 years are in one column and dogs under 1 year have different column. I want to be abel to select dogs that are between 8 - 12 years in age and count them. This is my query but it only selects one dog with certain age.

@checkup = Dog.where(age: 8).count

Upvotes: 0

Views: 37

Answers (2)

max
max

Reputation: 101811

As suggested by Pavan you could use a range to create a BETWEEN query.

@checkup = Dog.where(age: 8..12).count

But this approach is still flawed since you have to periodically update all your records as time passes!

Instead use a Date column to record the birthdate of the dogs.

rails g migration AddBirthdateToDogs birthdate:date
rake db:migrate

Then you can select the dogs by:

Dog.where(birthdate: 8.years.ago..12.years.ago

Or if you want to be fancy you can create a class method:

class Dog < ActiveRecord::Base
  # Select dogs by age
  # @param [Range, Fixnum] age
  # @return [ActiveRecord::Relation]
  # @example
  #   Dog.aged(0)
  #   Dog.aged(1..2) 
  def self.aged(age)
    if age.respond_to?(:map)
      age = age.map do |x|
        x.is_a?(Date)? x : x.years.ago  
      end 
      age = age.first..(age.last + 1.year)
    elsif age.respond_to?(:year)
      age = age.year.ago..(age + 1.year)
    end
    self.where(birthdate: ago)
  end
end

Upvotes: 1

Pavan
Pavan

Reputation: 33542

If I understood correctly, the below should work

@checkup = Dog.where(age: 8..12).count

which returns the count of the dogs which are between 8-12.

Upvotes: 0

Related Questions