Rails scope that does nothing for NOT IN values

前端 未结 4 1913
北荒
北荒 2021-02-13 22:53

I have a Rails 3 scope that excludes an array of ids.

What is the best way to write the scope so that it does nothing when the array is empty and is still chainable? I c

相关标签:
4条回答
  • 2021-02-13 23:22

    If the ids array is empty then don't return anything.

    scope :excluding_ids, lambda { |ids|
      where(['id NOT IN (?)', ids]) if ids.any?
    }
    

    The query will run without any additional constraints on the query if there are no ids.

    0 讨论(0)
  • 2021-02-13 23:28

    In Rails 4 you can use:

    scope :excluding_ids, ->(ids) { where.not(id: ids) }
    
    0 讨论(0)
  • 2021-02-13 23:29

    Here's a slight variation on Douglas' answer, using ruby 1.9 stabby lambda syntax and without the brackets in the where method.

    scope :excluding_ids, ->(ids) {where("id NOT IN (?)", ids) if ids.any?}
    
    0 讨论(0)
  • 2021-02-13 23:33

    How about the following? (It still checks for an empty array though, so if that's what you're trying to avoid it's not much of an improvement :)

    scope :excluding_ids,
         lambda {|ids| (ids.empty? && relation) || where('id not in (?)', ids) }
    
    0 讨论(0)
提交回复
热议问题