executing named_scoped only when there are present params
Hi have a model like this:
class EventDate < ActiveRecord::Base
belongs_to :event
named_scope :named, lambda { | name | {
:joins => { :event => :core},
:conditions => ["name like ?", "%#{ name }%"]
}}
named_scope :date_range, lambda { | start, length | {
:conditions => ["day >= ? AND day <= ?", start, date + (length || 30) ]
}}
it works correctly if i launch name = "ba" start = Date.today E开发者_StackOverflow中文版ventDate.named(name).date_range(start , start + 2)
But if the name or the start is nil i don't want execute the named_scope like name = nil EventDate.named(name).date_range(start , start + 2)
Is possible to set a condition inner the named_scope ?
thanks
Yes, just do:
unless name.blank?
Inside the lambda. In this way you can also set a default query to execute if the param is not given
Named_scope was not intended to handle that kind of logic. It was built to help you set certain conditions that might arise often.
The caller should call appropriate named_scope depending on params available, i.e. just add a condition before calling named_scope. For example:
if name.blank?
EventDate.date_range(start, end)
else
EventDate.named(name).date_range(start, end)
end
That being said, technically you could do something similar within a scope itself. Lambda created for the named_scope needs to return a hash and you could put your check in it (but please don't do this!) and return empty hash if name is empty. For example:
named_scope :named, lambda { | name |
name.blank? ? {} : { :conditions => ["name like ?", "%#{ name }%"] }
}
精彩评论