开发者

Use the same parameters many times in a find conditions: hash

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开发者_Python百科 to the variable to match all the "?" in the :conditions ?

thanks, P.


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.


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)]} }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜