简体   繁体   中英

Rails callback changed attribute

I've got a before_save callback in my User model :

before_save :notify_management, :if => lambda { |u| u.approved }

The goal of this was when people change approved from false to true that the management be notified. However once they change to true, and make any kind change on User model, this one gets invoked and I don't want that. I want it to invoke only when changing from non true (nil or false) value to true .

How can I accomplish that?

So first lets look at what your code actually does,

You are triggering the before_save callback so any time a record is created or updated :notify_management will be called. With the added conditional, :notify_management is called whenever a record is saved AND the users approved attribute is true (anything except false or nil ).

You want to only do it if the attribute is changed from false to true. So use:

before_save :notify_management, :if => lambda { |u| u.approved && u.approved_changed? }

By adding the second part, it will only trigger if that attribute has changed (from false=>true or true=>false) and combine it with what you already had it will only trigger when the value changed from false=>true

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM