How to return an empty ActiveRecord relation?

前端 未结 9 1942
有刺的猬
有刺的猬 2020-12-07 07:38

If I have a scope with a lambda and it takes an argument, depending on the value of the argument, I might know that there will not be any matches, but I still want to return

9条回答
  •  隐瞒了意图╮
    2020-12-07 08:28

    Use scoped:

    scope :for_users, lambda { |users| users.any? ? where("user_id IN (?)", users.map(&:id).join(',')) : scoped }
    

    But, you can also simplify your code with:

    scope :for_users, lambda { |users| where(:user_id => users.map(&:id)) if users.any? }
    

    If you want an empty result, use this (remove the if condition):

    scope :for_users, lambda { |users| where(:user_id => users.map(&:id)) }
    

提交回复
热议问题