Trần Kim Dự
Trần Kim Dự

Reputation: 6102

Rails: PG::ConnectionBad (connection is closed)

I'm using native query in Rails (because my query is complicated, and I don't think it can express in ActiveRecord). So here is how I try:

get  do
  connection = ActiveRecord::Base.connection.raw_connection
  connection.prepare('order_statistic', @@sql)
  data = connection.exec_prepared('order_statistic', [params[:id]])
  connection.close()
  data
end

This code run successfully for first time. But second time, It will throw exception. (I'm using PostgresSQL)

PG::ConnectionBad (connection is closed)

If I remove line connection.close. I will meet another exception:

PG::DuplicatePstatement (ERROR: prepared statement "order_statistic" already exists

Please help me how to use raw query correctly.

thanks

Upvotes: 1

Views: 3760

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6692

To do raw query you may follow this:

ActiveRecord::Base.connection.execute(%{YOUR QUERY HERE})

The reason in your code is you already close connection to database, so you can't do further query, to reconnect the db you can call reconnect! like:

ActiveRecord::Base.connection.reconnect!

But I won't recommend you do it, rails already help you handle it, don't do it yourself, let use my first suggestion to complete all raw query!

Upvotes: 5

Related Questions