views:

75

answers:

3

I'm trying to find the results of a model where it queries as the result of two conditions.

I have a search tag that looks for

 Model.find(:all, :conditions => "name LIKE params[search]")

but I'd like for the search to find all records where "name LIKE params[search] or description LIKE params[search] .

Is there any way to add an OR into a condition in rails?

or should I make an if statement?

A: 

Model.find(:all, :conditions => "name LIKE '%#{params[:search]}%' OR description like '%#{params[:search]}%'")

this might work for you.

Vamsi
Using the search params directly like that will make the query vulnerable to SQL injection attacks.
John Topley
Is there a way to do without that vulnerability?
ChrisWesAllen
+1  A: 

In RAILS 2.3 (uses parameters instead of pure SQL code for help with injection)

Model.all(:conditions=>['name LIKE ? OR name like ?','%'+@term_one+'%', '%'+@term_two+'%'])

I also really like to use Condition Builder for ActiveRecord in RAILS 2.x projects, because you can do:

Condition.block{|c|
  c.and :published, true
  c.and {|d|
    d.or :full_text, "LIKE", "%#{options[:qs]}%" 
    d.or :full_text, "LIKE", "%#{options[:qs]}%" 
  }
end

Note: Postgres users should use ILIKE (case insensitive like) instead of LIKE.

Note 2: Rails 3.0 would use the where clause chaining, which is pretty cool, and should have an OR operator added soon ActiveRelation GitHub -- but it'll look like User.where(:name => 'bob').or(:name=>'same')

Jesse Wolgamott
+1  A: 

For Rails 2.x you can use this query, which isn't vulnerable to SQL injection attacks:

Model.all(:conditions => ["name LIKE ? OR description LIKE ?",
  "%#{params[:search]}%", "%#{params[:search]}%"])
John Topley