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

On Sun, Nov 14, 2010 at 7:35 PM, KT [email protected] wrote:

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:

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


Hassan S. ------------------------ [email protected]
twitter: @hassan

On Mon, Nov 15, 2010 at 11:35 AM, KT [email protected] wrote:

: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]


Erol M. Fornoles

http://twitter.com/erolfornoles
http://ph.linkedin.com/in/erolfornoles

Erol F. wrote in post #961514:

On Mon, Nov 15, 2010 at 11:35 AM, KT [email protected] wrote:

: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,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

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.

On Mon, Nov 15, 2010 at 6:24 PM, Erol F.
[email protected]wrote:

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 M. Fornoles

http://twitter.com/erolfornoles
http://ph.linkedin.com/in/erolfornoles

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: