0

So I set a variable in my main ruby file that's handling all my post and get requests and then use ERB templates to actually show the pages. I pass the database handler itself into the erb templates, and then run a query in the template to get all (for this example) grants.

In my main ruby file:

grants_main_order = "id_num"
get '/grants' do
    erb :grants, :locals => {:db=>db, :order=>grants_main_order, :message=>params[:message]}
end

In the erb template:

db = locals[:db]
getGrants = db.exec("SELECT * FROM grants ORDER BY $1", [locals[:order]])

This produces some very random ordering, however if I replace the $1 with id_num, it works as it should.

Is this a typing issue? How can I fix this? Using string replacement with #{locals[:order]} also gives funky results.

3 Answers 3

1

Parameters are there to put in constant values into the query. It's possible and legal, but not meaningful to use them in an ORDER BY-clause.

Say you want to issue this query:

SELECT first_name, last_name
  FROM people
 ORDER BY first_name

If you put "first_name" in a string and pass it in as a parameter, you instead get:

SELECT first_name, last_name
  FROM people
 ORDER BY "first_name"

The difference is huge. That last ORDER BY-clause really tells te database not to care about the column values for each row, and just sort as if all rows were identical. Sorting order will be random.

0

I would recommend using datamapper (http://datamapper.org/) for sinatra. It's a very slick ORM and handles the paramaterized queries you are trying to build quite well.

2
  • Ah, that would be great, except I'm not allowed to install any additional gems. It's for a school project, and although I'm not really worried about it, it made me curious. I'll consider DataMapper in the future if I continue to work with Ruby... For now, any alternative?
    – nathas
    Apr 30, 2010 at 16:02
  • The only other thing I would suggest is to use sprintf to construct your query string and make sure that the escape/conversion is correct. Apr 30, 2010 at 18:17
0

have you inspected what locals[:order] is? Maybe something funky in there.

p locals[:order]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.