PiKaY
PiKaY

Reputation: 289

How to create a common after_create callback for all models?

Consider I have the models User, Account and Products. I want a common after_create callback for all these models say log_creation.

How do I do that?

Upvotes: 3

Views: 2406

Answers (2)

Igbanam
Igbanam

Reputation: 6082

You can have a GenericModule and include this in any model you wish

module GenericModule
  extend ActiveSupport::Concern

  included do
    after_create :log_creation
  end

  def log_creation
    # perform logging
  end
end

And in the model

class User < ActiveRecord::Base
  include GenericModule

  # ...other model code...
end

You can have this for all your models in which you need this behavior.

Upvotes: 4

anothermh
anothermh

Reputation: 10564

From the Ruby on Rails Guides on ActiveRecord Callbacks:

Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.

Here's an example where we create a class with an after_destroy callback for a PictureFile model:

class PictureFileCallbacks
  def after_destroy(picture_file)
    if File.exists?(picture_file.filepath)
      File.delete(picture_file.filepath)
    end
  end
end

When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:

class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks.new
end

Upvotes: 1

Related Questions