1

I'm trying to build my conditions like so:

conditions = {}
conditions[:doors] = 4
conditions[:type] = "sedan"

Cars.find(:all, :conditions=>conditions)

How would I add to my conditions for 'LIKE' conditions:

conditions[:color] NOT LIKE '%black%'

1 Answer 1

2

If you have Rails 3+ consider using the new AREL syntax for some of your query building:

records = Car.where(:doors => 4, :type => "sedan")
records = records.where("color NOT LIKE ?", "%black%")

But if you are still using Rails 2.3 then the syntax looks like:

clauses = ["doors = ?", "type = ?"]
conditions = [4, 'sedan']

if some_reason
  clauses << "color NOT LIKE ?"
  conditions << "%robert%"
end



Cars.find(:all, :conditions => [clauses.join(" AND" ), *conditions])

Definitely more annoying than than the AREL syntax.

A side-benefit of this syntax is that when ActiveRecord replaces the ? it will sanitize the inputs for SQL injection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.