Coding active
Coding active

Reputation: 1680

Skipping callbacks on record create

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.

Upvotes: 5

Views: 8233

Answers (4)

Coding active
Coding active

Reputation: 1680

I found a much better solution after a bit of research

https://www.rubydoc.info/gems/activerecord-import/0.12.0/ActiveRecord%2FBase.import

users = [User.new(name: "Test1"), ....]

User.import(users)

Doesn't invoke callbacks or validations, and much faster when the intent is to create n number of records

Upvotes: 3

John Baker
John Baker

Reputation: 2398

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.

Upvotes: 1

sawa
sawa

Reputation: 168269

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.

Upvotes: 0

ekampp
ekampp

Reputation: 1959

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.

Upvotes: 9

Related Questions