I want to get the sql generated on running
.save
when I run this command in console
irb(main):018:0> a = User.last
irb(main):018:0> a.first_name
=> "Mohan"
irb(main):019:0> a.first_name = 'Sohan'
=> "Sohan"
irb(main):020:0> a.save
(2.0ms) BEGIN
SQL (1.4ms) UPDATE `users` SET `first_name` = 'Sohan', `updated_at` = '2017-02-15 14:00:10' WHERE `users`.`id` = 1
(31.3ms) COMMIT
=> true
This actually updates the record. I want to know the sql query generated without updating the record.
I tried using .to_sql but that seems to work only for relations.
You can use sandbox mode from your terminal: rails console --sandbox Which allows you to play with models, using all methods like: .create, .delete, .save, .update without affecting the original DB. Any modifications you make will be rolled back on exit.
UPDATE
You can achieve this goal with AREL from your terminal:
# Arel::InsertManager
table = Arel::Table.new(:users)
insert_manager = Arel::InsertManager.new
insert_manager.into(table)
insert_manager.insert([ [table[:first_name], 'Eddie'] ])
insert_manager.to_sql
# Arel::UpdateManager
table = Arel::Table.new(:users)
update_manager = Arel::UpdateManager.new
update_manager.set([[table[:first_name], "Vedder"]]).where(table[:id].eq(1)).table(table)
update_manager.to_sql
Here you can find all Arel managers, like delete_manager.rb, select_manager.rb and the others.
Good read: http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With