我想用“?”用于在 Rails 中的 MySQL 请求中进行搜索的字符。 比如经典的方式是:
Model.where("name = ?", '#{@search}')
我的问题是关于长查询和多行条件。 如果我想手动构建条件:
where = ""
where << " status = 1 "
where << " AND MATCH (name) AGAINST (? IN BOOLEAN MODE), @search " if @search
@records = Model.where(where)
当然不行。 那么如何使用“?” (为了安全和简单)多行条件?
一个简单的方法是:
where << " MATCH (name) AGAINST ('#{@search}' IN BOOLEAN MODE) "
但如果@search 包含引号,我将失去安全性(SQL 注入(inject))并且引号可能会出现问题。
谢谢,
最佳答案
您对 where 的内容有点困惑:您将变量名放在字符串中,这是行不通的:字符串中的“@search”字面意思是“@search”,而不是“@search”变量。
将 where
的参数视为对象数组的最佳方式,您可以像这样构建它。第一个对象是查询字符串(带有 ? 符号),其他元素是 ? 的值。符号,将由 rails 清理和翻译。
例如
User.where(["first_name = ? and last_name = ?", "John", "Smith"])
您可以将其他内容传递到 where,例如值的散列或单个字符串,但数组是最灵活的,尤其是在您的情况下。
考虑到这一点,您可以执行类似这样的操作来构建动态创建的复杂查询:我经常使用这种模式,因为它非常灵活且可读性强。
condition_strings = []
condition_values = []
condition_strings << "status = ?"
condition_values << 1 #or some dynamic data
condition_strings << "MATCH (name) AGAINST (? IN BOOLEAN MODE)"
condition_values << @search
conditions = [condition_strings.join(" AND ")] + condition_values
# => ["status = ? AND MATCH (name) AGAINST (? IN BOOLEAN MODE)", 1, "foo"]
#now we can use the array as an argument to `.where`:
@records = Model.where(conditions)
关于mysql - 如何使用 Ruby On Rails 编写 MySQL 多行条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427925/