在我的应用程序中,我有一个包含三列的客户模型,first_name
、middle_name
和 last_name
。我在执行搜索的模型中有一个方法:
class Customer < ActiveRecord::Base
belongs_to :user
def self.search(search, user)
if search
.where('first_name LIKE ? OR middle_name LIKE ? OR last_name LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
.where(user: user)
else
where(user: user)
end
end
end
此搜索功能的问题在于它一次只允许按三列之一进行搜索。
例如,客户的名字是“foo”,中间名是“bar”,姓氏是“baz”。单独搜索“foo”、“bar”或“baz”会返回结果,但“foo bar”或“bar baz”不会。 我允许在所有三列中进行搜索的最佳方式是什么?
最佳答案
您可以在数据库查询中连接您的字段
更新:
.where("concat_ws(' ' , first_name, middle_name, last_name) LIKE ?", "%#{search}%")
这应该适用于 foo
、foo bar
或 foo bar baz
但不是 foo baz
如果你也想支持foo baz
.where("first_name LIKE ? OR middle_name LIKE ?"\
" OR last_name LIKE ? OR concat_ws(' ' , first_name, middle_name, last_name) LIKE ?"\
" OR concat_ws(' ' , first_name, last_name) LIKE ?",
"%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
关于ruby-on-rails - Rails 在搜索中组合多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36586372/