Rails - named_scopes - conditional conditions

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 to apply this condition in rails only if user_id is not zero?

+2
source share
1 answer

Of course. You can put something in a lambda that you would do in any other Ruby block, so just change it to return a hash :conditionsonly when user_id is not zero. Here I used a simple ternary conditional:

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

All Articles