Ruby-on-rails 如何在 Arel 和 Rails 中执行 LIKE 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4430578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a LIKE query in Arel and Rails?
提问by filsa
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.
Arel 正确地包装了查询字符串 'Smith',但因为这是一个 LIKE 语句,所以它不起作用。
How does one do a LIKE query in Arel?
如何在 Arel 中执行 LIKE 查询?
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?
PS Bonus--我实际上是在尝试扫描表上的两个字段,名称和描述,以查看是否有任何匹配的查询。这将如何运作?
回答by Pedro Rolo
This is how you perform a like query in arel:
这是在 arel 中执行类似查询的方式:
users = User.arel_table
User.where(users[:name].matches("%#{user_name}%"))
PS:
PS:
users = User.arel_table
query_string = "%#{params[query]}%"
param_matches_string = ->(param){
users[param].matches(query_string)
}
User.where(param_matches_string.(:name)\
.or(param_matches_string.(:description)))
回答by Reuben Mallaby
Try
尝试
User.where("name like ?", "%#{params[:query]}%").to_sql
PS.
附注。
q = "%#{params[:query]}%"
User.where("name like ? or description like ?", q, q).to_sql
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)
Aaand 已经很长时间了,但是@cgg5207 添加了一个修改(如果您要搜索长名称或多个长名称参数,或者您懒得输入,这将非常有用)
q = "%#{params[:query]}%"
User.where("name like :q or description like :q", :q => q).to_sql
or
或者
User.where("name like :q or description like :q", :q => "%#{params[:query]}%").to_sql
回答by cgg5207
Reuben Mallaby's answer can be shortened further to use parameter bindings:
Reuben Mallaby 的回答可以进一步缩短以使用参数绑定:
User.where("name like :kw or description like :kw", :kw=>"%#{params[:query]}%").to_sql

