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

查看:34
本文介绍了如何在 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)))

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

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