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

eck*_*cki 3 ruby variables activerecord ruby-on-rails rails-activerecord

我正在使用Rails 4.2

我有两个都需要存在或都不存在的数据库调用,因此我在方法内部使用事务来实现。我还希望通过相同方法在其他位置访问我创建的变量。我是否只需要使用实例变量而不是局部变量?(为此,我puts以其他代码为例,计划执行的代码要比这复杂得多)。

def method_name
  ActiveRecord::Base.transaction do
    record = another_method(1)
    another_method(record)
  end
  puts record.id
end
Run Code Online (Sandbox Code Playgroud)

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

undefined local variable or method `record' for #<Class:...>
Run Code Online (Sandbox Code Playgroud)

但是更改record@record可以缓解这种情况。那真的是最好的选择吗?还是有更好/更优雅的方式?

Ale*_*kin 7

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
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我不跟。分配块内的局部变量并从块中返回它,分配外部变量,如上所示。`record = ActiveRecord::Base.transaction { r = another_method(1); another_method(r); r}`。 (2认同)