Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture errors from ActiveRecord::Base.connection.execute in Rails?

I want to run a raw SQL query as following:

ActiveRecord::Base.connection.execute(some_query);

Can I capture any errors that happen while executing the query? If yes, how? Does execute returns anything? It doesn't say in the documentation.

Cheers

like image 445
Priyank Avatar asked Dec 11 '09 11:12

Priyank


3 Answers

execute method is typically implemented by respective database adapters and returns Result object from respective database libraries. So, if you are using Mysql the return value will be of type Mysql::Result.

Typically, if there is an error, the method will simply raise an exception which can be rescued.

like image 31
Hemant Kumar Avatar answered Nov 19 '22 22:11

Hemant Kumar


You can rescue errors as normal. For example:

begin
  ActiveRecord::Base.connection.execute(some_query)
rescue
  # do stuff with exception
end

Have a look at the MySql (for example) adapter's code to see what's going on.

In this case, execute returns a MySql::Result object.

like image 179
Andy Stewart Avatar answered Nov 19 '22 21:11

Andy Stewart


I think I found the answer. Execute statement returns the error that it receives from the database and that can be captured in a variable and displayed.

like image 40
Priyank Avatar answered Nov 19 '22 22:11

Priyank