gpt4 book ai didi

ruby-on-rails - 如何获取 Rails 4 activerecord 插入 sql?

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:15 25 4
gpt4 key购买 nike

我想动态获取activerecord的sql语句。例如

pen = Pen.new
pen.description = "HB"
pen_sql = pen.insert_sql
puts pen_sql
=> "Insert into pens (description) values ('HB')"

最佳答案

您创建自己的方法来获取类似这样的插入语句。

def get_insert_sql(from_dbmodel)
insert_sql = from_dbmodel.class.arel_table.create_insert.tap do |im|
im.insert(from_dbmodel.send(:arel_attributes_with_values_for_create, from_dbmodel.attribute_names))
end.to_sql

return insert_sql
end

pen = Pen.new
pen.description = "HB"
pen_sql = get_insert_sql(pen)
puts pen_sql
=> "Insert into pens (description) values ('HB')"

在 rails 4 中测试

关于ruby-on-rails - 如何获取 Rails 4 activerecord 插入 sql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com