使用LIKE的ActiveRecord搜索模型仅返回完全匹配

时间:2013-03-13 12:10:20

标签: ruby-on-rails-3 activerecord

在我的rails应用中,我正在尝试根据特定条件搜索用户模型。

特别是,我有一个 location 字段,这是一个字符串,我想根据包含搜索字符串来搜索此字段。例如,如果我搜索位置为“牛津”的用户,我希望它也会返回具有相应变体的用户,例如“牛津,英格兰”。

在网上搜索了答案,似乎我应该在activerecord搜索中使用LIKE关键字,但对我而言,这只是返回完全匹配。

以下是搜索方法

中我的代码片段
conditions_array = []
conditions_array << [ 'lower(location) LIKE ?', options[:location].downcase ] if !options[:location].empty?
conditions = build_search_conditions(conditions_array)
results = User.where(conditions)

我做错了吗?或者使用LIKE不是正确的方法来实现我的目标?

1 个答案:

答案 0 :(得分:2)

您需要like '%oxford%'

%匹配任意数量的字符,即使是零字符

conditions_array << [ 'lower(location) LIKE ?', "%#{options[:location].downcase}%" ] if !options[:location].empty?