[英]How to access a variable that was created in a transaction?
我正在使用rails 4.2
我有两个db调用,它们都需要存在或者都不存在,所以我在一个方法中使用事务来做到这一点。 我还希望我创建的变量可以在同一方法中被其他地方访问。 我只需要使用实例变量而不是局部变量吗? (为此我使用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
将缓解这一点。 这真的是最好的选择吗? 还是有更好/更优雅的方式?
在方法范围内声明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
返回一个值并将其分配给记录:
def method_name
record, another_record =
ActiveRecord::Base.transaction do
[another_method(1), another_method(2)]
end
puts record.id if record
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.