Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Rails Active Records Callbacks: Part 1

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 172
    Comment on it

    Hi friends,

    Whenever you create,save or initialize an object there are so many things available in rails that are called Callbacks or Hooks. They can be used as checks between on stage of the object to another. In this chapter I am going to explain few of the callbacks available during creation and saving of the object. One by one I will explain each of them a bit. But before that lets see the use case of why callbacks are an important feature in rails active records.

    For example suppose you want to save phone number of a user and the user is free to enter the phone number either without any country code prefix or with country code prefix. So you want to check if the number is with country code you save it as it is in the db and if it is without country code you automatically add the country code before the number is even validated by its validates method. For fulfilling this use case their is a callback before_validation so if you pass a method inside before_validation it will be called before the validates of the model is called and you can write whatever code you want. Like in our case:
     

    class User < ActiveRecord::Base
        validates :phone_number, presence: true
       
        before_validation :set_phone_number
       
        def set_phone_number
             if phone_number.present? && (!phone_number.starts_with? '+91')
                 self.phone_number = '+91'+self.phone_number
             end
        end
    end

     

    Now try on console:
     

    rails c
    
    > u = TestUser.new
    => #<TestUser id: nil, phone_number: nil, created_at: nil, updated_at: nil>
    
    
    > u.phone_number = '9876543210'
    > u.save
      (0.2ms)  begin transaction
      SQL (0.6ms)  INSERT INTO "test_users" ("phone_number", "created_at", "updated_at") VALUES (?, ?, ?)  [["phone_number", "+919876543210"], ["created_at", "2016-06-08 16:20:39.466995"], ["updated_at", "2016-06-08 16:20:39.466995"]]
       (111.5ms)  commit transaction
    
    > u.phone_number
    => "+919876543210"


    Thus you have seen that +91 is automatically appended to the number. Similar to this there are so many other validations available in rails. In this chapter I am explaining those methods that comes into picture during creation or saving of a record:


    a) before_validation:

    It is called before the validates are called.


    b) after_validation:

    It is called after all the validations are performed but the objects is still not saved.


    c) before_save:

    It is called after the validations are performed and also the after_validates methods are executed but the object is still not saved. It gets called every time before the object is saved, either it is new or old.

     

    d) before_create:

    This method is also called at the same time after the validations are performed and also the after_validates methods are executed. But this gets called only when the object is newly created and not a persisted one.

     

    e) around_save:

    methods passed under around_save gets called during the object is being saved.

     

    f) before_update:

    It gets called before any update call is made to an existing object.


    g) around_update:

    Methods passed under around_update gets called during the object is being updated.


    h) around_create:

    Similar to around_save, except it is called only during creation of a new record not a persisted one.


    i) after_save:

    It gets called after the object is saved. It works for both the new and persisted records.


    j) after_create:

    It gets called after the object is created. Works only for new records.

     

    k) after_update:

    It works after the object is updated.

     

    l) after_commit/after_rollback:

    These callback operations are performed when the objects are successfully replicated into the DB or removed from DB.

     

    Hope you liked this blog. In my next blog I will write some other types of useful callbacks of active records.

 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: