0

我有以下搜索方法:

 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

It be nice if you could loop through the options and then the options that selected run the query that matches that, then when the options hash reaches the end remove the ORfrom the LIKE ? OR

4

1 回答 1

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 。

于 2013-10-24T15:07:04.020 回答