JP Silvashy
JP Silvashy

Reputation: 48555

rails, activerecord callbacks not saving

I have a model with a callback that runs after_update:

after_update :set_state

protected

def set_state
  if self.valid?
    self.state = 'complete'
  else
    self.state = 'in_progress'
  end
end  

But it doesn't actually save those values, why not? Regardless of if the model is valid or not it won't even write anything, even if i remove the if self.valid? condition, I can't seem to save the state.

Um, this might sound dumb, do I need to run save on it?


update

Actually, I can't run save there because it results in an infinite loop. [sighs]

Upvotes: 0

Views: 714

Answers (3)

Will
Will

Reputation: 8282

after_update works on the object in memory not on the record in the table. To update attributes in the DB do the following

after_update :set_state

protected

def set_state
  if self.valid?
    self.update_attribute('state', 'complete')
  else
    self.update_attribute('state', 'in_progress')
  end
end 

Upvotes: 1

Alex Korban
Alex Korban

Reputation: 15136

Judging by the fact that the examples in ActiveRecord documentation do things like this:

def before_save(record)
  record.credit_card_number = encrypt(record.credit_card_number)
end

def after_save(record)
  record.credit_card_number = decrypt(record.credit_card_number)
end

you do need to save the record yourself.

Upvotes: 1

klew
klew

Reputation: 14977

after_update is run after update, so also after save. You can use update_attribute to save this value, or just call save (I'm not sure if there don't be any recurence). Eventualy you can assign it in before_update (list of availble options is here). On the other side invalid object will not be saved anyway, so why you want to assign here the state?

Upvotes: 1

Related Questions