Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • before_save And after_destroy callbacks in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 7.71k
    Comment on it

    Sometimes while developing applications, need arises that we have to get some operation performed either before or after the execution of some method.

    For these purposes rails provide us with some nice hooks or we can say callbacks which can be called before or after the execution of some method.

    Today we are going to see two very important callbacks namely before_save and after_destroy.

    • before_save

    The before_save method is written inside the model class where you want to call it.

    The before save method contains a method name which is called exactly before the object of the same class is saved into the database. 

    For example lets say we have a user model. As soon as we are about to save the user we want a method to be called before save which creates a one time password (OTP) for that user. 

    So we can execute this process like this

    class user < ApplicationRecord
      before_save :create_otp
      def create_otp
        @otp = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
      end
    end

    so the create method will be called before saving the user.

    • after_destroy

     The after_destroy method is also written inside the model class where you want to call it.

    The after_destroy method contains a method name which is called exactly after the object of the same class is deleted or we can say destroyed from the database.

    Suppose an example where a user has many blogs. A user's blogs should be destroyed if the user is destroyed. Let's add an after_destroy callback to the User model by way of its relationship to the Blog model:

    class User < ApplicationRecord
      has_many :blogs, dependent: :destroy
    end
     
    class Blog < ApplicationRecord
      after_destroy :log_destroy_action
     
      def log_destroy_action
        puts 'Blog destroyed'
      end
    end
     
    >> user = User.first
    => #<User id: 1>
    >> user.blogs.create!
    => #<Blog id: 1, user_id: 1>
    >> user.destroy
    Blog destroyed
    => #<User id: 1>

    So hope this blog was helpful to understand both these 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: