gpt4 book ai didi

ruby-on-rails - 搜索查询 (name or forename) and (name forname) and (forname name)

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:17 25 4
gpt4 key购买 nike

我是 Rails 的初学者,在改进我的搜索查询时遇到了一些问题:

在我调用的 Controller 中:

def index
if params[:search]
@persons = Person.search(params[:search]).order("created_at DESC")
else
@persons = Person.order("created_at DESC")
end
end

在我的模型中:

 def self.search(query)
where("name like ?", "%#{query}%")
end

所以实际上我只过滤名称!现在我试图改进它,但我并不喜欢它,我的目标是用户可以输入例如:

 John
Smith
Smith John
John Smith

它总是应该返回 John Smith。那么我该如何编写这么长的sql查询呢?提前致谢!

最佳答案

此搜索方法应该适合您:

def self.search(query)
return where('FALSE') if query.blank?

conditions = []
search_columns = [ :vorname, :nachname ]

query.split(' ').each do |word|
search_columns.each do |column|
conditions << " lower(#{column}) LIKE lower(#{sanitize("%#{word}%")}) "
end
end

conditions = conditions.join('OR')
self.where(conditions)
end
  • 此代码是安全的:在调用 SQL 之前清理字符串
  • 此代码很灵活:您可以非常轻松地添加更多列进行搜索
  • 这段代码是灵活的:您可以轻松地分割不仅仅是空间(-/| 等)
  • 此代码可用于链作用域
  • 此代码不区分大小写,适用于 John SmithJohN SMITh

如有需要,请随时提问!

关于ruby-on-rails - 搜索查询 (name or forename) and (name forname) and (forname name),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19934616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com