ActiveRecord 哪里字段=?可能值数组
ActiveRecord where field = ? array of possible values
我想做
Model.where('id = ?', [array of values])
如何在不将 OR 语句链接在一起的情况下完成此查找?
从 here 开始,它似乎是使用 SQL in
语句完成的:
Model.where('id IN (?)', [array of values])
或者更简单地说,正如 kdeisz 指出的那样(使用 Arel 创建 SQL 查询):
Model.where(id: [array of values])
来自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])
为了便于阅读,可以进一步简化为:
Model.find_by(id: [array of values])
这相当于使用where
,但更明确:
Model.where(id: [array of values])
如果您正在寻找 mongoid 中的查询,这就是一个Model.where(:field.in => ["value1", "value2"] ).all.to_a
和 find_by 之间存在 'small' 差异。
find_by 将 return 如果找到则只有一条记录,否则将为零。
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
同时其中它将return一个关系
Returns a new relation, which is the result of filtering the current relation
according to the conditions in the arguments.
因此,在您的情况下,适当的代码是:
Model.where(id: [array of values])
您可以使用 'in' 运算符:
Model.in(id: [array of values])
我想做
Model.where('id = ?', [array of values])
如何在不将 OR 语句链接在一起的情况下完成此查找?
从 here 开始,它似乎是使用 SQL in
语句完成的:
Model.where('id IN (?)', [array of values])
或者更简单地说,正如 kdeisz 指出的那样(使用 Arel 创建 SQL 查询):
Model.where(id: [array of values])
来自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])
为了便于阅读,可以进一步简化为:
Model.find_by(id: [array of values])
这相当于使用where
,但更明确:
Model.where(id: [array of values])
如果您正在寻找 mongoid 中的查询,这就是一个Model.where(:field.in => ["value1", "value2"] ).all.to_a
和 find_by 之间存在 'small' 差异。
find_by 将 return 如果找到则只有一条记录,否则将为零。
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
同时其中它将return一个关系
Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.
因此,在您的情况下,适当的代码是:
Model.where(id: [array of values])
您可以使用 'in' 运算符:
Model.in(id: [array of values])