Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 881
ecki Avatar asked Dec 19 '18 05:12

ecki


1 Answers

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
like image 142
Aleksei Matiushkin Avatar answered Oct 06 '22 18:10

Aleksei Matiushkin