executing named_scoped only when there are present params

Posted by Luca Romagnoli on Stack Overflow See other posts from Stack Overflow or by Luca Romagnoli
Published on 2010-05-23T14:20:45Z Indexed on 2010/05/23 14:40 UTC
Read the original article Hit count: 298

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 EventDate.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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord