我的出发点基本上是瑞恩贝茨Railscast。
我有用户模型,我需要做一些查询。该模型具有以下几个小时费率属性:
#User migration
...
t.decimal :hour_price_high
t.decimal :hour_price_low
...
我的查询工作在User.where(Array)格式,其中Array格式化
["users.hour_price_high <= ? OR users.hour_price_low >= ? OR users.hour_price_low <= ? AND users.hour_price_high >= ?", hour_price_high, hour_price_low, hour_price_low, hour_price_high]
#This is simply a search of two ranges. Search for $40/h - $60/h.
#It will return an User who charge any overlapping price range. Such as one who charges $45/h - $65/h, etc.
我只想在where语句中将其转换为Ruby语法。
#This isn't the full query shown above..
User.where(:high_price_high => hour_price_low..hour_price_high, :hour_price_low => hour_price_low..hour_price_high)
生成此SQL:
=> "SELECT `users`.* FROM `users` WHERE (`users`.`hour_price_high` BETWEEN 45 AND 60) AND (`users`.`hour_price_low` BETWEEN 45 AND 60)"
当然,由于AND,这是错误的。我需要它:
=> "SELECT `users`.* FROM `users` WHERE (`users`.`hour_price_high` BETWEEN 45 AND 60) OR (`users`.`hour_price_low` BETWEEN 45 AND 60)"
如何在没有从我的二年级E.E.课程中删除旧真值表的情况下将其作为OR语句?
谢谢!
答案 0 :(得分:1)
当你在一个where
方法中链接多个where
方法或者有一些参数时,你总是在它们之间得到AND,所以当你想要OR时你需要使用这个语法:< / p>
User.where("users.hour_price_high <= ? OR users.hour_price_low >= ? OR users.hour_price_low <= ? AND users.hour_price_high >= ?", hour_price_high, hour_price_low, hour_price_low, hour_price_high)
注意:请观看http://railscasts.com/episodes/202-active-record-queries-in-rails-3以获取有关有效记录查询的详细信息。