gpt4 book ai didi

ruby-on-rails - 在 ActiveRecord 中执行后回滚

转载 作者:行者123 更新时间:2023-12-03 19:41:33 24 4
gpt4 key购买 nike

我正在为 Rails 中的 sqlite3 db 构建一个沙箱,以便人们可以自己查询数据。现在我只是像这样调用执行:
@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 .

关于ruby-on-rails - 在 ActiveRecord 中执行后回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229004/

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