开发者

Rails - named_scopes - conditional conditions

开发者 https://www.devze.com 2022-12-21 18:02 出处:网络
If I have the following named_scope 开发者_JAVA技巧named_scope :scope_by_user_id, lambda {|user_id| {:conditions => [\"comments.user_id = ?\", user_id]}}

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] }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号