Using like in multiple conditions

From the beta version of the Agile book V2, I can understand the
following:

User.find(:all, :conditions => [“name like ?” , params[:name]+"%" ])

yet_more = Order.find(:all,
:conditions => [“name = :name and pay_type = :pay_type”,
params[:order]])

What I want to do is to use the like operator for the name in this
second example, but I am getting cofused in how the condition should be
coded?

Thanks

Andrew

You can modify the value of params[:order] in your controller/action.

def results
params[:order][:name] += ‘%’
yet_more = Order.find(:all, :conditions => [“name LIKE :name AND
pay_type = :pay_type”, params[:order]])
end

This will add the % operator to the end of the name string being passed
from the submitted form.

-Jared

Jared, that works. Thanks a lot.

I had to modify it slightly as the name parameter could be nil so I
used:

params[:order][:name] = params[:order][:name].to_s + ‘%’

That works for me, I’m not sure if there is a more elegant or better way
of dealing with name being nil.

Andrew

Consider wrapping this up in a custom finder on Order… that way you
can

  1. put conditions in the model and do evaluations on the fields
    there…
    keeping controller nice and clean.
  2. unit test this a lot easier

If the params[:order][:name] parameter is left blank on your search
form, you could do something like this in your controller:

unless params[:order][:name].blank?
params[:order][:name] += ‘%’
else
params[:order][:name] = ‘%’
end
yet_more = Order.find(:all, :conditions => [“name LIKE :name AND
pay_type = :pay_type”, params[:order]])

That way, if the field is left blank on the search form, the
Order.find() method will include all names, and just match on the
pay_type. I don’t know if I’d call it more elegant, but it’s a bit
more explicit in what the code is doing.

-Jared

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs