Find_by_sql and passing parameter value

Any idea why I cant pass parameter value for the find_by_sql query ?
simple example below wont work:

loginid = “demo”

sql = ‘SELECT * FROM users where ownerid = “loginid”’

@imitems = Imitem.find_by_sql(sql);

but if I change query to this it works:

sql = ‘SELECT * FROM users where ownerid = “demo”’

On 6 May 2008, at 13:38, KTU wrote:

Any idea why I cant pass parameter value for the find_by_sql query ?
simple example below wont work:

loginid = “demo”

sql = ‘SELECT * FROM users where ownerid = “loginid”’

Read up on your ruby. How’s ruby to know that loginid refers to a
variable rather than just the string loginid.
#{} and connection.quote are your friend.
But before you do that, why on earth are you using find_by_sql?
ImItem.find :all, :conditions => {:ownerid => loginid}
is easier to understand and you have less chance of shooting yourself
in the foot.

Fred

Im using it since I have very complex query. I just put here simple
example. And yes I tried “#{loginid}” but it wont pass the variable.

On May 6, 3:56 pm, Frederick C. [email protected]

On 6 May 2008, at 14:28, KTU wrote:

Im using it since I have very complex query. I just put here simple
example. And yes I tried “#{loginid}” but it wont pass the variable.

Because your string is using single quotes. Single quotes don’t
interpolate.

Fred

You’re not using parameterized SQL. Try:

@imitems = Imitem.find_by_sql(‘select * from users where ownerid = ?’,
loginid)

HTH,

-Roy

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