开发者

Rails - named_scopes - conditional conditions

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜