【问题标题】:Rails query where attribute equals foo or barRails 查询属性等于 foo 或 bar
【发布时间】:2014-09-04 20:41:31
【问题描述】:

有没有办法写

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")

心灵是快乐的。

【问题讨论】:

  • 你的意图的问题是 "foo" || "bar" 在 ActiveRecord 可以用它做任何事情之前评估为 "foo"

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


【解决方案1】:

在该位置传递数组['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')

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 2020-02-02
    • 2017-07-25
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多