Rails: How to find_by a field containing a certain string
SqlRuby on-RailsRuby on-Rails-3Ruby on-Rails-3.1Sql Problem Overview
I have a model named Topic, that has a name as a field.
So say I have a term I'm searching for, apple.
If I do a
Topic.find_by_name("apple")
I get a record back with the name apple. That's good -- but how do I change find_by_name so that it can find "apple juice" as well as "apple" -- basically, find names that contain the original query or exactly match the original query?
Edit: Thanks for all the response. I guess I should've been a little more clear earlier, but what if I want to find by a variable name (obviously I'm not going to want to find by the name "apple" everytime :) )?
How do I manipulate Topic.where to accommodate for this? So something like...
@topic = Topic.where(......., @name)
Sql Solutions
Solution 1 - Sql
I think something like this should work:
Topic.where("name like ?", "%apple%")
To accomodate for your edit:
Topic.where("name like ?", "%#{@search}%")
Basic string interpolation, you're using the value of @search
inside the string %%
, so you @search = "apple"
then you end up with %apple%
Solution 2 - Sql
With PostgreSQL you can also use match operators:
Topic.where("name ~* ?", @search)
Solution 3 - Sql
Looks like in Rails 3 you would want to use the where:
Topic.where("name ILIKE ?", "%apple%")
Solution 4 - Sql
Don't put string directly like that. Its called SQL injection. You should instead use .where
:
Topic.where("name like '?%' ", params[:name])
Solution 5 - Sql
Try
Topic.where("name like ?",'%apple%')
Topic.find(:all, :conditions => ["name like ?","%apple%"])