如何在 Arel 和 Rails 中进行 LIKE 查询? [英] How to do a LIKE query in Arel and Rails?

查看:24
本文介绍了如何在 Arel 和 Rails 中进行 LIKE 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

SELECT * FROM USER WHERE NAME LIKE '%Smith%';

我在 Arel 的尝试:

My attempt in Arel:

# 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}%"))

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)))

这篇关于如何在 Arel 和 Rails 中进行 LIKE 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆