开发者

Complex SQL Query in Rails - User.where(hash)

My starting point is basically Ryan Bates Railscast.

I have User model that I need to do some queries on. The model has a couple hourly rate attributes as follows:

#User migration
...
t.decimal :hour_price_high
t.decimal :hour_price_low
...

I have the query working in the User.where(Array) format where Array is formatted

["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.

I simply wish to convert this into Ruby syntax in the where statement开发者_运维知识库.

My problem is how to represent the OR.

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

Produces this SQL:

 => "SELECT `users`.* FROM `users` WHERE (`users`.`hour_price_high` BETWEEN 45 AND 60) AND (`users`.`hour_price_low` BETWEEN 45 AND 60)"

Which, of course, is wrong because of the AND. I need it to be:

=> "SELECT `users`.* FROM `users` WHERE (`users`.`hour_price_high` BETWEEN 45 AND 60) OR (`users`.`hour_price_low` BETWEEN 45 AND 60)"

How can I make this be an OR statement without busting out the old truth table from my sophomore E.E. classes?

Thanks!


When you chain several where methods or have a few arguments in one where method, then you always get AND between them, so when you want to have OR you need to use this syntax:

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)

Note: please watch http://railscasts.com/episodes/202-active-record-queries-in-rails-3 in order to get more information about active record queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜