Bill
Bill

Reputation: 3209

Rails ActiveRecord, checking for nil

Let c be anything, (or nil) is:

if !c.nil?
  true
else
  false
end

The same as

if c
  true
else
  false
end

Also, is:

Model.where(:name => params[:foo])

The same as:

Model.where('name = ?', params[:foo])

Coming from a Java background, does the hash method of passing to a #where() offers escaping? Is there an advantage of using one or the other?

Upvotes: 0

Views: 70

Answers (1)

Andrew Hubbs
Andrew Hubbs

Reputation: 9436

In both cases, yes these are identical. Also, yes, the hash format does offer escaping. It actually will do more than that depending on if params[:foo] is a list it will change between an = and an in (possibly more things too).

In the future, you can easily see what SQL the AREL statement generates by using the to_sql method.

Model.where(:name => params[:foo]).to_sql

Generally, the convention is to use the hash syntax when it is sufficient. It is usually easier to read, especially when you have queries that involve multiple models. For example:

Model.joins(:other_model).where(:name => params[:foo], :other_model => {:attr => params[:bar]})

Upvotes: 1

Related Questions