Is there a way to use @today in a model ??

I'm trying to get records from a has_many that are only from this year.

has_many :visit, :conditions => "year = #{@today.year}", :dependent => :destroy

This has trouble. it thinks @today is null.. Any other ideas?


Don't you want :visits (with an s?)

has_many :visits, :conditions => "year = SQL_FUNCTION_THAT_RETURNS_CURRENT_YEAR",.....

Replacing "SQL_FUNCTION...YEAR" with whatever works for your database.

If you want to specify the year, look into using a lambda for the conditions...


What is @today?


I don't think you can use a lambda on the :conditions option to find/has_many...

but you can do it with a named scope

  has_many :visits, :dependent => destroy   named_scope :this_year, lambda { { :conditions => { :year => } }}

Then to get the visits this year for a model referred to by the variable model


Alternatively, you could have a slightly different named scope which would let you specify the year at run-time, assuming that @today might not always, e.g. if you are using the user's timezone.

named_scope :in_year, lambda { |year| {:conditions => {:year => year}}

Then you could use


The reason you need to express this a a lambda is twofold:

1) has_many and named_scope are evaluated in the context of the active record class, so @today is not an instance variable but a class instance variable, which is probably why it is nil.

2) more importantly, @today is being evaluated at the time the association declaration is executed (during class definition time). If you want to use the value at the time you make the query, it needs to be a lambda so that the value gets evaluated each time.


try using a range in the condition... Post.all(:conditions=>{:created_at=>})

you can also create a named scope (rails 2.3) in the belongs_to end of the relationship class Post < ActiveRecord::Base   named_scope :from_this_year, lambda { { :conditions=>{:created_at =>}} end need to use a lambda, otherwise the time value from app load is used... which obviously wouldn't be what you want.

you would use it like so User.first.posts.from_this_year

or you could set up a has_many class User < ActiveRecord::Base

has_many :posts_from_this_year, :class_name=>"Post", :conditions=>{:created_at=>} end @user.posts_from_this_year