在 ActiveRecord 中执行后回滚

Rollback after Execute in ActiveRecord

我正在 Rails 中为 sqlite3 数据库构建一个沙箱,以便人们可以自己查询数据。现在我只是像这样调用执行:

@results = ActiveRecord::Base.connection.execute(params[:query])

在破坏性命令的情况下,我想在每次得到结果后回滚。这样做的好方法是什么?

这里我为你准备了一些:

Active Record class ActiveRecord::Base has method called connection() which returns valid connection to MySQL (or some other) database using config/database.yml database settings.

Return value of connection() method is an object of class MysqlAdpater (or [some-other-database]Adapter). Here are some useful methods of that object:

  • execute - executes SQL query. For "SELECT ..." query will return Mysql::Result class (or other result-set class for your Ruby database interface).
  • insert - executes SQL query and returns last inserted id
  • update, delete - executes SQL query and returns number of affected rows
  • begin_db_transaction - executes SQL query 'BEGIN' (transaction start)
  • commit_db_transaction - executes SQL query 'COMMIT' (confirm transaction)
  • rollback_db_transaction - executes SQL query 'ROLLBACK' (rollback transaction)

There is also methods select_all and select_one, but we do not recommend using it, because of inefficient implementation trying to fetch all selected values to memory.

看看这个 Documentation