我是 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 Smith
或JohN SMITh
如有需要,请随时提问!
关于ruby-on-rails - 搜索查询(名称或名字)和(名称名称)和(名称名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19934616/