Can I see what SQL an ActiveRecord .save call would generate, without doing the save?

Viewed 450

For an ActiveRecord query, I can see the SQL generated without actually executing it:

SomeModel.where(something: "something").to_sql

No query was sent to the DB, but I can see the SQL as a string.

Is there anything similar that can be done for the update SQL that will be generated by some_model.save?

I think maybe not, I can't find it!

4 Answers

Even I have not seen any method to generate sql for save yet.

I also faced a situation earlier and I found that we can use the sandbox mode of rails console to verify the queries and it will be rollback the changes made in the session once we close the console.

rails console --sandbox

documentation

If you wish to test out some code without changing any data, you can do that by invoking rails console --sandbox.

@Rohan Daxini have added the reason why .to_sql is not available on save

I have this situation too.

I'm considering doing a restore of a production backup in a local environment, doing the update there and using mysqldump.

Do save within a transaction with a rollback at the end eg.

irb(main):024:0> Post.transaction do
irb(main):025:1* p=Post.create(user_id: User.first.id, text: '11', group_id: 1)
irb(main):026:1> raise ActiveRecord::Rollback
irb(main):027:1> end
Related