开发者

rails, activerecord callbacks not saving

开发者 https://www.devze.com 2022-12-29 11:18 出处:网络
I have a model with a callback that runs after_update: after_update :set_state protected def set_state if self.valid?

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]


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?


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.


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号