Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I want to execute a rather nasty recursive update query in rails. This means I want to write some raw postgres sql, with parameters, and execute it inside a rails controller.

How do I do that? I can't find a PreparedStatement class in activerecord, there don't seem to be any methods named 'native', I have tried ActiveRecord::Base.connection.exec_delete, I have looked through the source - just cannot, cannot work it out.

I've looked everywhere - the documentation goes in circles.

How would I tell postgres to execute

delete from foo where foo.bar=?

bind 'baz' to the q-mark, and do it without using the active record objects, finders, you-beaut subset thingies and all the rest.

I just want to execute a prepared statement with some bindings. How hard can it be?

(PS, and no: I don't want to jam the parameters into the string myself and execute it as unparameterised sql. It's wrong and it means I have to worry about sanitising the data.)

share|improve this question
    
Are you trying to create some sort of ETL system? –  Chandranshu Nov 21 '13 at 7:27

1 Answer 1

up vote 2 down vote accepted

See the discussion of PreparedStatements in Rails ('Using Prepared Statements') here - http://blog.daniel-azuma.com/archives/216 . Shows you which methods to call, and how to format your arguments.

UPDATE:

Paraphrased from the post:

For the delete method arguments use the template first, followed by a query name (which can be nil) and then an array of values to inject into the statement. So like this:

row_count = connection.delete("DELETE FROM foo WHERE foo.bar=$1", nil, [[nil, 'baz']])
share|improve this answer
    
Thank you, this is what I needed to know. Only issue now is - where in the documentation is this? How was I supposed to find out for myself that this is how to do it? … ok, I found the doco in connection aciverecord/connectionadapters/databasestatements, but it's not terribly helpful. I have to say - I'm finding the "code by cookbook example" aspect of Ruby development not to my liking. But thanks. I can proceed with this. –  PaulMurrayCbr Nov 21 '13 at 12:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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