我想获取运行时生成的sql
.save
当我在控制台中运行这个命令时
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
这实际上更新了记录。我想知道在不更新记录的情况下生成的sql查询。
我尝试使用 .to_sql
但这似乎只适用于关系。
最佳答案
您可以从您的终端使用沙盒模式:rails console --sandbox
它允许您使用模型,使用所有方法,如:.create
, .delete
, .save
, .update
不影响原始数据库。您所做的任何修改都将在退出时回滚。
更新
您可以使用 AREL 实现此目标从您的终端:
# 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您可以找到所有 Arel 管理器,例如 delete_manager.rb、select_manager.rb 和其他。
好读:http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html
关于mysql - 将保存/更新调用 rails 转换为 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251546/