Reputation: 239
While using the command:
@items = Item.find(:all,:order => 'name', :conditions => ["name LIKE ?", "%#{params[:key]}%"])
This works perfectly fine, but the search is only based on just a column. How do i make it search other columns, like description, category?
Upvotes: 2
Views: 2284
Reputation: 1040
What if you have 15 columns to search then you will repeat key 15 times. Instead of repeating key 15 times in query you can write like this:
key = "%#{params[:key]}%"
@items = Item.where('name LIKE :search OR description LIKE :search OR category LIKE :search', search: key).order(:name)
It will give you same result.
Thanks
Upvotes: 1
Reputation: 53349
I am assuming you are using Rails 2, since you are using ActiveRecord 2 style syntax. You can just add the other columns as additional conditions, like this:
key = "%#{params[:key]}%"
@items = Item.find(:all, :conditions => [
'name LIKE ? OR description LIKE ? OR category LIKE ?',
key, key, key
], :order => 'name')
For reference, here's how you would do it in Rails 3:
key = "%#{params[:key]}%"
@items = Item.where('name LIKE ? OR description LIKE ? OR category LIKE ?', key, key, key).order(:name)
Upvotes: 5