Wednesday, January 25, 2006

Using Parameters with a string

I posted my first question to the Ruby on Rails list and got an answer right away.

My question:

Hello,

I am learning Ruby on Rails and have a very basic question.

def self.home_categories (portal_id)
find(:all,
:conditions => "portal_id=:portal_id"
)
end

How can I put the value of portal_id in the string "portal_id=...". I tried concatenation but I get the error that it cannot convert.

I can figure it out eventually but thought someone may have the answer ready.

Thanks
Frank



The answers I received:

From Justin Bailey
Easy, ruby can embed expressions into strings:


def self.home_categories (portal_id)
find(:all,
:conditions => "portal_id=#{portal_id}"
)
end




The #{..} syntax acts like ruby code inside your string, so the value
of portal_id gets into your conditions.

Now, the fact you are putting this value directly into a SQL statement
might be troubling - it it's from some sort of form submission or URL
you are opening yourself to SQL injection attacks there.


Eric Goodwin said:

Hey, You probably want something like this


def self.home_categories (portal_id)
find(:all, :conditions => [ "portal_id=?", portal_id ] )
end

2 Comments:

At 1:40 AM, Blogger phprorsolutions said...

:conditions =>[ " name like ?", '".params[:keyword]."%'])


what is correct syntax of this line of code ?????????

 
At 1:40 AM, Blogger phprorsolutions said...

:conditions =>[ " name like ?", '".params[:keyword]."%'])


what is correct syntax of this line of code ?????????

 

Post a Comment

<< Home

eXTReMe Tracker