Using Like Clauses
You might be tempted to do something like the following to use
parameterized
like clauses in conditions:
Doesn’t work
User.find(:all, :conditions => [“name like ‘?%’” , params[:name]])
Rails doesn�t parse the SQL inside a condition and so doesn�t know that
the
name is being substituted into a string. As a result, it will go ahead
and add
extra quotes around the value of the name parameter. The correct way to
do
this is to construct the full parameter to the like clause and pass that
parameter
into the condition.
Works
User.find(:all, :conditions => [“name like ?” , params[:name]+"%" ])
Also, what if I have an array coming from the form and what to put the
values into a IN() clause, i.e
…WHERE dept_id IN (1,2,3,4,5)
doing
:conditions => [“dept_id IN (?)”, params[:email].join(’,’)]
will not do anything useful.
:conditions => [“dept_id IN (?)”, params[:email]]
AR will automatically join your array (it must be an array!).
Tiago M.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.