如何在 Arel 和 Rails 中进行 LIKE 查询?
我想做类似的事情:
SELECT * FROM USER WHERE NAME LIKE '%Smith%';
我在 Arel 中的尝试:
# params[:query] = 'Smith'
User.where("name like '%?%'", params[:query]).to_sql
但是,这变成了:
SELECT * FROM USER WHERE NAME LIKE '%'Smith'%';
Arel 正确包装了查询字符串“Smith”,但因为这是一个 LIKE 语句,所以它不起作用。
如何在 Arel 中进行 LIKE 查询?
PS Bonus——我实际上正在尝试扫描表上的两个字段,即名称和描述,以查看是否有与查询匹配的字段。那会如何运作呢?
I want to do something like:
SELECT * FROM USER WHERE NAME LIKE '%Smith%';
My attempt in Arel:
# params[:query] = 'Smith'
User.where("name like '%?%'", params[:query]).to_sql
However, this becomes:
SELECT * FROM USER WHERE NAME LIKE '%'Smith'%';
Arel wraps the query string 'Smith' correctly, but because this is a LIKE statement it doesnt work.
How does one do a LIKE query in Arel?
P.S. Bonus--I am actually trying to scan two fields on the table, both name and description, to see if there are any matches to the query. How would that work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是在 arel 中执行类似查询的方法:
PS:
This is how you perform a like query in arel:
PS:
尝试
PS。
Aaand 已经很久了,但是 @cgg5207 添加了修改(如果您要搜索长名称或多个长名称参数或者您懒得输入,则非常有用)
或
Try
PS.
Aaand it's been a long time but @cgg5207 added a modification (mostly useful if you're going to search long-named or multiple long-named parameters or you're too lazy to type)
or
Reuben Mallaby 的答案可以进一步缩短以使用参数绑定:
Reuben Mallaby's answer can be shortened further to use parameter bindings:
不要忘记转义用户输入。
您可以使用
ActiveRecord::Base.sanitize_sql_like(w)
您可以在
models/user.rb
中进行简化Don't forget escape user input.
You can use
ActiveRecord::Base.sanitize_sql_like(w)
You can simplify in
models/user.rb