Mostafa Hussein
Mostafa Hussein

Reputation: 11960

changed? method not work inside model

I have the following model:

class TicketStatus < ActiveRecord::Base
  after_update :set_previous_staff
  attr_accessible :status_id, :ticket_id , :staff_id, :advisor_id, :previous_advisor_id, :previous_staff_id
  belongs_to :status
  belongs_to :ticket
  belongs_to :staff, class_name: 'Staff', foreign_key: 'staff_id'
  belongs_to :previous_staff , class_name: 'Staff', foreign_key: 'previous_staff_id'
  belongs_to :advisor, class_name: 'Advisor', foreign_key: 'advisor_id'

  def set_previous_staff
    self.previous_staff_id = self.staff_id_was if self.staff_id_changed?
  end

end

set_previous_staff method is not working with the callback however i tried changed? in console and it should work , what is missing here ? i am using rails 3.2.14

what i expected: I have an assigned employee to a ticket , i need when that assigned employee changed, his id should be added to previous_staff_id , so this will let me know who is the current employee and who was before him.

Upvotes: 0

Views: 1534

Answers (1)

Tyler
Tyler

Reputation: 11499

You're changing the instance after you update it, but you never actually save the change to the database after that. For updating, the order goes:

  1. before_validation
  2. before_validation_on_update
  3. after_validation
  4. after_validation_on_update
  5. before_save
  6. before_update
  7. DATABASE INSERT
  8. after_update
  9. after_save

Try changing after_update to before_update so that your method runs before the change is committed.

Upvotes: 1

Related Questions