Rails查询属性等于foo或bar的位置

时间:2014-09-04 20:41:32

标签: sql ruby ruby-on-rails-4

有没有办法写

Model.where("attribute = ? OR attribute = ?", "foo", "bar")

使用像(错误)

这样的对象
Model.where(attribute: "foo" || "bar")

特别适用于链接,例如:

Model.where(attr_one: "blaz").where("attr_two = ? OR attr_two = ?", "foo", "bar")

变得(错误地)

Model.where(attr_one: "blaz", attr_two: "foo" || "bar")
心灵很高兴。

1 个答案:

答案 0 :(得分:3)

在该位置传递数组['foo', 'bar']将导致查询生成IN ()子句,相当于您的attr_two = ? || OR attr_two = ?

Model.where(attr_one: 'blaz', attr_two: ['foo', 'bar'])
# Or chained:
Model.where(attr_one: 'blaz').where(attr_two: ['foo', 'bar'])

应该产生如下查询:

SELECT model.* FROM model WHERE model.attr_one = 'blaz' AND model.attr_two IN ('foo', 'bar')