我需要创建一个搜索查询,查找具有指定小时费率的所有用户。用户有小时费率范围,如55美元/小时至75美元/小时。网站访问者将使用另一个范围搜索这些用户,例如$ 40 / h到$ 60,这应该显示所有重叠的注册用户。
旧的工作纯字符串查询是:
(users.hour_price_low BETWEEN :low_price AND :high_price OR hour_price_high BETWEEN :low_price AND :high_price).
我需要将其重构为可在数组查询中搜索。重构的起点是RailsCast。
我已经修改了方法来容纳OR子句,没有问题。
##This is where I am getting hung up. I can't get the syntax correct.##
def low_price_or_conditions
["users.hour_price_low BETWEEN ?", price_low..price_high] unless price.blank?
end
def high_price_or_conditions
["users.hour_price_high BETWEEN ?", price_low..price_high] unless price.blank?
end
最后:
@users = User.where(conditions)
哪个输出此错误:
Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80 OR users.hour_pr' at line 1: SELECT `users`.* FROM `users` WHERE (users.hour_price_low BETWEEN 60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80 OR users.hour_price_high BETWEEN 60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80)
我愿意接受任何建议。谢谢!
答案 0 :(得分:2)
略过范围,只需像以前一样使用between子句。
即
["users.hour_price_low BETWEEN ? AND ?", price_low, price_high]
答案 1 :(得分:0)
我认为你想在内部范围内查找两个不同的值(hour_price_high和hour_price_low),因此你可以尝试在SQL中使用IN谓词。
def low_price_or_conditions
["users.hour_price_low IN (?)", price_low..price_high] unless price.blank?
end
def high_price_or_conditions
["users.hour_price_high IN (?)", price_low..price_high] unless price.blank?
end
虽然我不太确定条件“除非”是否正是你想要的。从RailsCast中我了解到这意味着如果用户没有选择按该属性进行搜索,则跳过将此过滤器添加到搜索/查找过滤器中。