将保存/更新调用轨道转换为 sql [英] Convert save/update call rails to sql
问题描述
我想在运行时生成sql
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
这实际上更新了记录.我想知道在不更新记录的情况下生成的sql查询.
This actually updates the record. I want to know the sql query generated without updating the record.
我尝试使用 .to_sql
但这似乎只为关系工作.
I tried using .to_sql
but that seems to work only for relations.
推荐答案
您可以从终端使用沙箱模式: rails console --sandbox
它允许您使用模型,使用所有方法,例如: .create
, .delete
, .save
, .update
不影响原始数据库.您所做的任何修改都将在退出时回滚.
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.
更新
您可以使用终端中的 AREL 实现此目标:
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
在这里您可以找到所有 Arel 经理,例如 delete_manager.rb、select_manager.rb 等.
Here you can find all Arel managers, like delete_manager.rb, select_manager.rb and the others.
好书:http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html
这篇关于将保存/更新调用轨道转换为 sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!