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%'
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.
精彩评论