Search multiple db columns in Rails 3.0
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 simpl开发者_StackOverflow社区e statement?
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}%"}])
精彩评论