重构搜索过滤器

时间:2013-10-24 15:02:31

标签: ruby-on-rails

我有以下搜索方法:

 def search(search = nil, field_search1,field_search2, field_search3,field_search4,field_search5)
      if search
        where("#{field_search1} LIKE ? OR #{field_search2} LIKE ? OR #{field_search3} LIKE ? OR #{field_search4} LIKE ? OR #{field_search5}LIKE ?", "%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%")
      else
        where(nil)
      end
    end

它有效,但非常难看。尝试重构它,所以我传入选项哈希中的字段名称。做类似的事情:

def search(search= nil, options={})
  options.each do |option|
    #Run the query inside here 
end

如果您可以遍历选项然后选择的选项运行与其匹配的查询,那么很好,然后当选项哈希到达结尾时从OR中删除LIKE ? OR

1 个答案:

答案 0 :(得分:0)

这应该有效:

def search(search = nil, fields)
  query_string = fields.join(' LIKE :search OR ') + ' LIKE :search'
  (search) ? where(query_string, search: search) : where(nil)
end

虽然我不允许在没有搜索查询的情况下运行该方法。另外,请查看全文搜索:http://robots.thoughtbot.com/post/58438017998/implementing-multi-table-full-text-search-with-postgres