Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Apply Active Record Observer on a Particular Column

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 132
    Comment on it

    Meaning:-

    Active Record Observers means a callback or a trigger which will get called in the life cycle of active record object. This is used for the purpose of reducing the burden on model's functionality which is not directly belongs to model. e.g. a task like after registration send an email to user.

    Creation:-

    The Observers can be created by following command

    script/generate observer node

    The above command will generate an observer with name NodeObserver in node_observer.rb file and this will by default observers a Node model.

    Configuration:-

    Then need to configuration in a config/environment.rb as

    config.active_record.observers = :node_observer

    There are 16 types of callback available in active record as follows:-

    CALLBACKS = [ :after_initialize, :after_find, :after_touch, :before_validation, after_validation,:before_save, :around_save, :after_save, :before_create, :around_create, :after_create, :before_update, :around_update, :after_update,:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback ]
    But all these callbacks works on a row object but suppose we wanted to observe a particular column has changed or not then we can use an Active Record's change? method . e.g. suppose for security purpose we want to send an email to a user when he changes his password

    def after_update(user) 
        if user.password_changed? 
           //email send code// 
        end 
     end
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: