Forum: Ruby on Rails contoller code mysteries

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.
Craig W. (Guest)
on 2006-02-03 17:54
(Received via mailing list)
In my controller...this code works

  def list2
    first_name = params[:client][:first_name]
    @myclients = Client.find(:all, :conditions =>
      ["first_name = :first_name", {:first_name => first_name}])
  end

this code doesn't...

  def list2
    first_name = params[:client][:first_name]
    if first_name
      searchstring = '["first_name = :first_name", {:first_name =>
first_name}]'
    end

    @myclients = Client.find(:all, :conditions => searchstring)
  end

it results in error...

RuntimeError: ERROR     C42601  Msyntax error at or near
"["    P30     Fscan.l L573
Ryyerror: SELECT * FROM clients WHERE (["first_name = :first_name",
{:first_name => first_name}])

Why or more specifically, how do I accomplish this since I want to test
each field from the search form for presence of field data and string
this together for an 'or' type search.

Craig
Steve R. (Guest)
on 2006-02-03 19:40
(Received via mailing list)
Try parameterizing your queries. It protects against sql injection
attacks:

@foo = Client.find(:all, :conditions => ['first_name = ?',
some_variable])

I think this will serve you better. I'm writing this code out of my
head, so
you may need to relook the syntax.
Łukasz Piestrzeniewicz (Guest)
on 2006-02-03 20:53
(Received via mailing list)
Hi,

On 03/02/06, Craig W. <removed_email_address@domain.invalid> wrote:
>   end
Try this:

 def list2
   first_name = params[:client][:first_name]
   if first_name
     conditions = ["first_name = :first_name", {:first_name =>
first_name}]
   end

   @myclients = Client.find(:all, :conditions => conditions)
 end

There is no magical evaluation of string into array. If it expects an
array you have to give it an array. A string with ruby syntax
describing an array won't do.
Craig W. (Guest)
on 2006-02-04 01:34
(Received via mailing list)
On Fri, 2006-02-03 at 19:50 +0100, Łukasz Piestrzeniewicz wrote:
> >     end
> first_name}]
>    end
>
>    @myclients = Client.find(:all, :conditions => conditions)
>  end
>
> There is no magical evaluation of string into array. If it expects an
> array you have to give it an array. A string with ruby syntax
> describing an array won't do.
----
I see...said the blind man.

Thanks Lukasz, Steve, Andrej...that makes perfect sense to me now...I of
course simply see the same language...rails sees the objects.

Craig
This topic is locked and can not be replied to.