如何在 Arel 和 Rails 中执行 LIKE 查询?
问题描述:
我想做类似的事情:
SELECT * FROM USER WHERE NAME LIKE '%Smith%';
我在阿雷尔的尝试:
# params[:query] = 'Smith'
User.where("name like '%?%'", params[:query]).to_sql
然而,这变成了:
SELECT * FROM USER WHERE NAME LIKE '%'Smith'%';
Arel 正确地包装了查询字符串Smith",但因为这是一个 LIKE 语句,所以它不起作用.
Arel wraps the query string 'Smith' correctly, but because this is a LIKE statement it doesnt work.
如何在 Arel 中执行 LIKE 查询?
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?
答
这是在 arel 中执行类似查询的方式:
This is how you perform a like query in arel:
users = User.arel_table
User.where(users[:name].matches("%#{user_name}%"))
附注:
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)))