我正在尝试动态获取activerecord的sql语句。
例如

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

最佳答案

您可以创建自己的方法来获取类似这样的insert语句。

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')"

在轨道4中测试

09-17 19:14