How to return an empty ActiveRecord relation?

前端 未结 9 1764
有刺的猬
有刺的猬 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

    It is possible and so that's:

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

    http://apidock.com/rails/v4.0.2/ActiveRecord/QueryMethods/none

    Correct me if I'm wrong.

    0 讨论(0)
  • 2020-12-07 08:29

    I think I prefer the way this looks to the other options:

    scope :none, limit(0)
    

    Leading to something like this:

    scope :users, lambda { |ids| ids.present? ? where("user_id IN (?)", ids) : limit(0) }
    
    0 讨论(0)
  • 2020-12-07 08:31

    There are also variants, but all of these are making request to db

    where('false')
    where('null')
    
    0 讨论(0)
提交回复
热议问题