views:

36

answers:

2

Hello, I have a model who holds 2 properties: valid_from and valid_to.

I need to select all instances that are currently valid, i.e. valid_from <= today and valid_to >= today.

i have the following find :

Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", Date.today, Date.today])

I already thought about storing Date.today in a variable and calling that variable, but i still need to call it twice.

my_date = Date.today
Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", my_date, my_date])

Is there a way to improve and do only one call to the variable to match all the "?" in the :conditions ?

thanks, P.

+1  A: 

I would use named_scope. In model add:

named_scope :valid, 
            :conditions => 
             ["valid_from <= ? and valid_to >= ?", Date.today, Date.today]

And then in your controller you can call:

@mymodels = Mymodel.valid

I think that focusing on reducing two calls to Date.today to only one call is wasting of time. It won't make your application faster or using less memory.

klew
i accept this answer for the last bit: there may be a way, but there is no point/particular benefit.Thanks
Pierre
The is a problem with using Date.today inside a named_scope. This is because the names scope is compiled when the activerecord model is first compiled. So, the call to Date.today is evaluated as this is a method call during the first time its found. On subsequent calls, this value will be fixed. So, its a good idea to take the value of the date as an input.Read more about this known issue at http://jitu-blog.blogspot.com/2009/07/looking-into-rails-namedscope.html
Sohan
+1  A: 

I'm not aware of a way to do what you're asking, but even if you could I don't think it would buy you much. I would create a named scope within your model class.

In this example, you can pass the date to the named scope, or it will default to today's date if no date is specified:

named_scope :by_valid_date, lambda { |*args|
            { :conditions => ["valid_from <= ? and valid_to >= ?",
              (args.first || Date.today), (args.first || Date.today)]} }
John Topley