Forum: Ruby on Rails Adding the conditions when parameter is available

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joshua P. (Guest)
on 2009-03-01 02:25
(Received via mailing list)
Hi all,

How do we add a conditions in a ActiveRecord find method when the
parameter is available?

Lets say I want to add this category conditions when the parameter
from the client:
Product.find(:all, :conditions => [ "c.id = ?", params[:catid])

Can we dynamically add that conditions to the find method when it is
available? Or do I have to manually make an conditional statement when
the parameter is available then give a different find method?

Thanks in advance.

--
If you can't believe in God the chances are your God is too small.

Read my blog: http://joshuajava.wordpress.com/
Follow me on twitter: http://twitter.com/jpartogi
Michael G. (Guest)
on 2009-03-01 03:36
(Received via mailing list)
I often do the brute-force approach:

  cond_string = []
  cont_hash = {}

  if params[:search_name]
    cond_string << "(name ILIKE :name)"
    cond_hash[:name] = "%#{params[:search_name]}%"
  end
  if params[:search_address]
    cond_string << "(address ILIKE :name)"
    cond_hash[:address] = "%#{params[:search_address]}%"
  end

conditions = cond_string.join(" AND ")
Person.all :conditions => [ conditions, cond_hash ]

--Michael
Frederick C. (Guest)
on 2009-03-01 04:54
(Received via mailing list)
On Mar 1, 1:35 am, Michael G. <removed_email_address@domain.invalid> wrote:
>     cond_string << "(address ILIKE :name)"
>     cond_hash[:address] = "%#{params[:search_address]}%"
>   end
>
> conditions = cond_string.join(" AND ")
> Person.all :conditions => [ conditions, cond_hash ]
>

The merge_conditions method (which was protected in previous versions
of rails) and the scoped named_scope are also handy for this sort of
thing.

Fred.
Joshua P. (Guest)
on 2009-03-01 05:28
(Received via mailing list)
Wow this is a very clean approach. Trying this one out. :-)

Thanks heaps.
Phlip (Guest)
on 2009-03-01 05:45
(Received via mailing list)
Joshua P. wrote:
> Wow this is a very clean approach. Trying this one out. :-)

>>   cond_string = []
>>   cont_hash = {}
>>
>>   if params[:search_name]
>>     cond_string << "(name ILIKE :name)"
>>     cond_hash[:name] = "%#{params[:search_name]}%"
>>   end

It also prevents SQL injection attacks:

   http://imgs.xkcd.com/comics/exploits_of_a_mom.png
This topic is locked and can not be replied to.