2

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.)

1
  • Are you trying to create some sort of ETL system? Commented Nov 21, 2013 at 7:27

1 Answer 1

2

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']])
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.