If I have the following named_scope
开发者_JAVA技巧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?
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] }
}
精彩评论