简体   繁体   中英

Check if a model was modified or created on before_save event

I want to check if a model is being created in the before_save callback of Rails. I also want to check if it has been modified (when updating).

Thanks

You can use new_record? to see if you have a brand new object and changed? to see if anything has changed:

before_save :pancakes

def pancakes
    if new_record?
        # Not in the database yet.
    elsif changed?
        # Already exists but it has unsaved changes.
    end
end

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