Search multiple db columns in Rails 3.0

风格不统一 提交于 2020-01-02 23:17:16

问题


I'm trying to write a statement that searches 2 db columns and returns results. Can this be done easily without the use of a gem like Searchlogic?

def self.search(search)
  if search
    find(:all, :conditions => ['city LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

What I have so far is a statement that performs a search on the city field of my database. However, I'd like to include functionality to cover the case of someone searching by state.

So if someone types 'CA' the search will return every listing in California. If the user types 'Los Angeles' the listing in Los Angeles will be returned. So in short, I'd like to query 2 db fields at the same time and return appropriate results. Can this be done with a simple statement?


回答1:


The best thing to do would be to implement a fulltext solution like solr or sphinx. Alternatively, if you want to keep things as simple as possible for now, you would just OR the search:

def self.search(search)
  if search
    find(:all, :conditions => ['city LIKE ? OR state LIKE ?', ["%#{search}%"]*2].flatten)
  else
    find(:all)
  end
end

UPDATE: syntax alternative (better) via Jeffrey W.

find(:all, :conditions => ['city LIKE :search OR state LIKE :search', {:search => "%#{search}%"}])


来源:https://stackoverflow.com/questions/5422489/search-multiple-db-columns-in-rails-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!