views:

137

answers:

2

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.

A: 

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.

Joshua Smith
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?
alleywayjack
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.
Joshua Smith
A: 

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

p locals[:order]

ba