如何访问在事务中创建的变量?

How to access a variable that was created in a transaction?

我正在使用 rails 4.2

我有两个数据库调用都需要存在或都不存在,所以我在一个方法中使用 t运行sactions 来做到这一点。我还希望我正在创建的变量可以被其他地方以相同的方法访问。我是否只需要使用实例变量而不是局部变量? (为此,我使用 puts 作为其他代码的示例,计划执行的代码比那复杂得多)。

def method_name
  ActiveRecord::Base.transaction do
    record = another_method(1)
    another_method(record)
  end
  puts record.id
end

如果我运行这段代码,它抛出这个:

undefined local variable or method `record' for #<Class:...>

但将 record 更改为 @record 将缓解这种情况。那真的是最好的选择吗?或者有什么better/more优雅的方法吗?

在方法范围内声明 record

def method_name
  record = nil # ⇐ THIS

  ActiveRecord::Base.transaction do
    record = another_method(1)
  end
  puts record.id #⇒ ID or NoMethodError if `another_method` did not succeed
end

一般来说,这种方法是一种代码味道,在大多数现代语言中都是被禁止的(其中内部 record 将被关闭而外部保持不变。)正确的方法可能是使 transaction 到 return 一个值并将其分配给记录:

def method_name
  record, another_record =
    ActiveRecord::Base.transaction do
      [another_method(1), another_method(2)]
    end
  puts record.id if record
end