ActiveRecord where field = ? array of possible values

后端 未结 6 1140
無奈伤痛
無奈伤痛 2020-12-13 07:47

I want to do

Model.where(\'id = ?\', [array of values])

How do I accomplish this look up without chaining OR statements together?

相关标签:
6条回答
  • 2020-12-13 08:32

    If you are looking for a query in mongoid this is the oneModel.where(:field.in => ["value1", "value2"] ).all.to_a

    0 讨论(0)
  • 2020-12-13 08:33

    There is a 'small' difference between where and find_by.

    find_by will return just one record if found otherwise it will be nil.

    Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.

      def find_by(*args)
          where(*args).take
        rescue RangeError
          nil
      end
    

    meanwhile where it will return an relation

    Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.

    So, in your situation the appropriate code is:

    Model.where(id: [array of values])
    
    0 讨论(0)
  • 2020-12-13 08:35

    For readability, this can be simplified even further, to:

    Model.find_by(id: [array of values])
    

    This is equivalent to using where, but more explicit:

    Model.where(id: [array of values])
    
    0 讨论(0)
  • 2020-12-13 08:35

    You can use the 'in' operator:

    Model.in(id: [array of values])
    
    0 讨论(0)
  • 2020-12-13 08:49

    From the ActiveRecord Query Interface guide

    If you want to find records using the IN expression you can pass an array to the conditions hash:

    Client.where(orders_count: [1,3,5])
    
    0 讨论(0)
  • 2020-12-13 08:51

    From here it appears to be done using an SQL in statement:

    Model.where('id IN (?)', [array of values])
    

    Or more simply, as kdeisz pointed out (Using Arel to create the SQL query):

    Model.where(id: [array of values])
    
    0 讨论(0)
提交回复
热议问题