如何将事务逻辑应用于 Rails 中的非数据库操作



>我在视图中有一个带有输入框的表单。如果填写输入框并按"保存",则会执行系统命令并将值保存到数据库中。

我检查命令是否已成功执行,然后检查值是否已更新到数据库。我不做的是在某种"事务"中运行它们,以便更改完成 如果"system_command == true".update == true.

嵌套条件可能是错误的做法,因为如果.update失败,则系统命令已经执行并且无法撤消。

  def update
    if system_command # Checks If command was executed successfully
      respond_to do |format|
        if @system_command.update(system_command_params)
          format.html { redirect_to system_commands_path, notice: 'Success' }
        else
          format.html { render :index }
        end
      end
    else
      redirect_to system_commands_path, notice: 'Failed'
    end
  end

system_command 是一种执行系统命令的方法。

我如何 100% 确定此方法操作的完整性?

您可以在保存记录之前对其进行验证:

@system_command.assign_attributes(system_command_params) # Assign params, but don't save.
# `system_command` will only be run if the @system_command passes Rails validations.
if @system_command.valid? && system_command
  @system_command.save
  # ...
end

请注意,调用 valid? 时不会考虑本机数据库约束

我相信

这个解决方案有效,但我还无法测试它。

  def update
    ActiveRecord::Base.transaction do
      @system_command.update(system_command_params) # Update the db
      begin
        system_command # Run the command
        redirect_to system_commands_path, notice: 'Success' 
      rescue # If the command fails
        raise ActiveRecord::Rollback
        redirect_to system_settings_path, notice: 'Fail'
      end           
    end
  end

最新更新