I'm using rails 4.2
I have two db calls that both need to exist OR both not exist, so I'm using transactions inside a method in order to do that. I also want the variable I am creating to be accessible by other places in the same method. Do I just need to use an instance variable instead of a local variable? (for this I am using puts
as an example of other code, the code am planning to execute is much more complicated than that).
def method_name
ActiveRecord::Base.transaction do
record = another_method(1)
another_method(record)
end
puts record.id
end
If I ran this code, it throws this:
undefined local variable or method `record' for #<Class:...>
but changing record
to @record
will alleviate this. Is that really the best option? Or is there a better/more elegant way?
Declare record
within method scope:
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
Generally speaking, this approach is a code smell and is prohibited in most modern languages (where inner record
would be closured and the outer remain unchanged.) The correct approach would be probably to make transaction
to return a value and assign it to the record:
def method_name
record, another_record =
ActiveRecord::Base.transaction do
[another_method(1), another_method(2)]
end
puts record.id if record
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With