Skipping callbacks on record create

Viewed 4006

I have a model A with an after_commit callback on create and update.

class A < ApplicationRecord
  after_commit :update_xyz, on: [:create, :update]
end

A rake task is in this use case. My rake task tries to create a number of model A records, but have to skip this update_xyz callback.

Is it possible to skip these callbacks while creating records? I would prefer not to add additional gems/plugins for this.

4 Answers

If you want a way to generally have the callback run, but at specific times be able to skip it, I usually go with this pattern:

class User < ActiveRecord::Base
  attr_accessor :skip_do_something

  after_save :do_something

  private

    def do_something
      return if skip_do_something
      # do work here
    end
end

This way it will generally always run the do_something callback, but it's possible to skip by doing:

user = User.find 1
user.skip_do_something = true
user.save

Hope this helps.

You can do it this way:

namespace :your_namespace do
  task :your_task => :environment do
    A.skip_callback(:commit, :after, :update_xyz)
    //do everything you need
    A.set_callback(:commit, :after, :update_xyz)
  end
end

For more information, you can check this link.

You can add a condition to your callback for example, like:

class A < ApplicationRecord
  after_commit :update_xyz, on: [:create, :update], unless :rake_task?
end

and defining rake_task? in some place appropriate.

Related