Home > Back-end >  Ruby on Rails, Instance variables is persisting through multiple requests
Ruby on Rails, Instance variables is persisting through multiple requests

Time:05-21

  def self.current_transaction_batch_id
    @current_transaction_batch_id ||= SecureRandom.hex
    @current_transaction_batch_id
  end

Hi, I have following method that is supposed to generate and return a batch id that I need to be unique for every request. But, the issue is that this method is returning the same value through multiple request which means the variable @current_transaction_batch_id is persisting through requests.

Thanks for help in advance

CodePudding user response:

What Alex said in the comments is correct:

The current_transaction_batch_id method is a class method. By setting the instance_variable @current_transaction_batch_id within it, you are setting it on the class, not the instance of the class. By memoizing it you are keeping it unchanged. The class is only loaded once and kept between requests, therefore the value never changes.

You'll need to change your code, so you are working on the instance, not the class:

  def current_transaction_batch_id
    @current_transaction_batch_id ||= SecureRandom.hex
  end
  • Related