Filter records by dates occurring this year

Hi all...

I'm trying to create a named_scope for people who were born this
year. I have an application helper method defining "current_year".

So far, I have this, but it's not filtering correctly. I think I need
a BETWEEN, maybe? I know this is something easy I'm just not
seeing... any help is appreciated!

class Person < ActiveRecord::Base
:named_scope :born_this_year, :conditions => {:dob => :current_year}
end

I'm trying to create a named_scope for people who were born this
year. I have an application helper method defining "current_year".

So far, I have this, but it's not filtering correctly. I think I need
a BETWEEN, maybe? I know this is something easy I'm just not
seeing... any help is appreciated!

class Person < ActiveRecord::Base

  Have you used a debugger or logging statements to see what the
  values of :dob and :current_year are at this point? :slight_smile:

Assuming your :dob is a date

Try :conditions => [‘dob BETWEEN ? AND ?’, Date.today.beginning_of_year, Date.today.end_of_year]

Wait let me correct that, but first, is :current_year a field or column in your table or a parameter that was meant to be passed to the named_scope?

Erol Fornoles wrote in post #961514:

:named_scope :born_this_year, :conditions => {:dob => :current_year}
end

Assuming your :dob is a date

Try :conditions => ['dob BETWEEN ? AND ?', Date.today.beginning_of_year,
Date.today.end_of_year]

Even better:

:conditions => ['year(dob) = ?', Date.today.year]

--
Erol M. Fornoles

Best,

Thanks for your responses everyone. Sorry for the delay in re-
posting, I've been away from computer.

@Erol :current_year is an application helper method to pull the
current year!
I'll try your suggestions, as well and report back. Thank you

@Hassan I will try a debugger, too - thanks for the reminder.

Thanks all -. I ended up having to use a lambda:

named_scope :born_this_year, lambda { |year| { :conditions => ['dob
between ? and ?', Date.today.beginning_of_year,
Date.today.end_of_year]}}

I love this group. :slight_smile: