即使before_save将其设置为nil,也会设置值

时间:2015-06-26 00:57:17

标签: ruby-on-rails activerecord sidekiq

我正在使用aasm_state gem以及sidekiq。以下是customer.rb对于aasm_state的定义的看法:

  aasm do
    state :closed, initial: true
    state :open
    state :claimed

    event :open do
      transitions from: :closed, to: :open
    end

    event :claim do
      transitions from: [:open, :closed], to: :claimed
    end

    event :close do
      transitions from: [:open, :claimed], to: :closed
      before do
        self.user_id = nil
      end
    end
  end

然后我也在customer.rb:

  def properly_close
    if closed? && user_id
      Rails.logger.info "Bad customer state with customer_id: #{id} at #{Time.now} and the last message was at #{messages.last.created_at}. Aasm_state_was: #{aasm_state_was}"
      self.user_id = nil
    end
  end

每当aasm_state =='关闭'时,客户端永远不应该有user_id。但是,它仍然经常发生。我认为它与sidekiq作业并行有关,但我不确定。即使我用两种方法确保user_id = nil(在之前和在proper_close中),它仍然最终设置为aasm_state =='closed'&& user_id

这怎么可能?我如何弄清楚它是如何发生的?

1 个答案:

答案 0 :(得分:4)

在这两种情况下,您都需要save更新,即:

self.user_id = nil
self.save

或者更简洁(和跳过回调):

self.update_attribute :user_id, nil