0

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
3
  • 1
    Try @checkup = Dog.where(age: 8..12).count Commented Oct 7, 2015 at 17:10
  • Yes! Thank. it works. What if I had to select multiple string values in a column? Commented Oct 7, 2015 at 17:14
  • Not sure what you are asking,try asking another question explaining what you need. Meanwhile please accept my answer :) Commented Oct 7, 2015 at 17:20

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

You can also use a DateTime but I doubt you need that level of precision.
I am going over the fancy method you gave and I am learning more. Thanks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.