views:

190

answers:

1

If I have the following named_scope

named_scope :scope_by_user_id, lambda {|user_id| {:conditions => ["comments.user_id = ?", user_id]}}

is there a way in rails to only apply that condition if user_id is not nil?

+3  A: 

Sure. You can put just about anything in a lambda that you would in any other Ruby block, so just modify it to return the :conditions hash only when user_id isn't nil. Here I've used a simple ternary conditional:

named_scope :scope_by_user_id, lambda {|user_id|
  user_id.nil? ? {} : { :conditions => ["comments.user_id = ?", user_id] }
}
Jordan