Ruby Rails,实例变量在多个请求中持续存在

Ruby on Rails, Instance variables is persisting through multiple requests

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

嗨,我有以下应该生成的方法和 return 我需要对每个请求都是唯一的批处理 ID。但是,问题在于此方法通过多个请求 return 获取相同的值,这意味着变量 @current_transaction_batch_id 通过请求持续存在。

提前感谢您的帮助

A​​lex在评论中说的是正确的:

current_transaction_batch_id 方法是 class 方法。通过在其中设置 instance_variable @current_transaction_batch_id,您是在 class 上设置它,而不是 class 的实例。通过记忆它,您可以保持它不变。 class 仅加载一次并在请求之间保留,因此该值永远不会改变。

您需要更改代码,因此您正在处理实例,而不是 class:

  def current_transaction_batch_id
    @current_transaction_batch_id ||= SecureRandom.hex
  end