Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • after_initialize and after_find Callbacks in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.90k
    Comment on it

    At the time of normal operations in rails application, the objects are either updated, created or destroyed or we create our defined methods in the controller. 

    Rails provide us with some hooks in the object life cycle which we can invoke before or after the execution of these methods so that we can control the flow of our application and data.

    These callbacks are methods that are called or get called in certain moments of object's life cycle.

    Today we are going to see three callbacks as follows: 

     

    • after_initialize

    At the time when an Active Record object is instantiated, the after_initialize method is always called.

    It gets invoked at the time of when a new object is created in order to access the database.

    Through this callback we don't have to override the active record function directly which helps in the smooth execution.

    class Employee < ApplicationRecord
      
      after_initialize do |employee|
        puts "The object has been initialized!"
      end
    
    end

    as soon as we will initialize the employee object , the after initialize method will be called and it will print the statement on the console like this

    >> Employee.new
    The object has been initialized!
    => #<Employee id: nil>

     

    • after_find

     

    The after_find callback will be always called at the time when Active Record loads a record from the database.

    after_find method is called before after_initialize if both of them are defined in the controller.

    class Employee < ApplicationRecord
      
      after_initialize do |employee|
        puts "The object has been initialized!"
      end
    
    
      after_find do |employee|
        puts "The object has been found!"
      end
    
    end

    as soon as we will fire a find query on the employee table and if both after_initialize and after_find methods are defined then first the after_find will be called and after that after_initialize will be called like this.

    >> Employee.first
    The object has been found!
    The object has been initialized!
    => #<Employee id: 1>

    So hope this was helpful to understand the after_initialize and after_find callbacks.

 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: