Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
More atrubyonrails.org:

Active Record Callbacks

This guide teaches you how to hook into the life cycle of your Active Recordobjects.

After reading this guide, you will know:

  • When certain events occur during the life of an Active Record object.
  • How to register, run, and skip callbacks that respond to these events.
  • How to create relational, association, conditional, and transactionalcallbacks.
  • How to create objects that encapsulate common behavior for your callbacks tobe reused.

1. The Object Life Cycle

During the normal operation of a Rails application, objects may becreated,updated, anddestroyed. ActiveRecord provides hooks into this object life cycle so that you can control yourapplication and its data.

Callbacks allow you to trigger logic before or after a change to an object'sstate. They are methods that get called at certain moments of an object's lifecycle. With callbacks it is possible to write code that will run whenever anActive Record object is initialized, created, saved, updated, deleted,validated, or loaded from the database.

classBirthdayCake<ApplicationRecordafter_create->{Rails.logger.info("Congratulations, the callback has run!")}end
irb>BirthdayCake.createCongratulations, the callback has run!

As you will see, there are many life cycle events and multiple options to hookinto these — either before, after, or even around them.

2. Callback Registration

To use the available callbacks, you need to implement and register them.Implementation can be done in a multitude of ways like using ordinary methods,blocks and procs, or defining custom callback objects using classes or modules.Let's go through each of these implementation techniques.

You can register the callbacks with amacro-style class method that calls anordinary method for implementation.

classUser<ApplicationRecordvalidates:username,:email,presence:truebefore_validation:ensure_username_has_valueprivatedefensure_username_has_valueifusername.blank?self.username=emailendendend

Themacro-style class methods can also receive a block. Consider using thisstyle if the code inside your block is so short that it fits in a single line:

classUser<ApplicationRecordvalidates:username,:email,presence:truebefore_validationdoself.username=emailifusername.blank?endend

Alternatively, you canpass a proc to the callback to be triggered.

classUser<ApplicationRecordvalidates:username,:email,presence:truebefore_validation->(user){user.username=user.emailifuser.username.blank?}end

Lastly, you can definea custom callback object, asshown below. We will cover these later in more detail.

classUser<ApplicationRecordvalidates:username,:email,presence:truebefore_validationAddUsernameendclassAddUsernamedefself.before_validation(record)ifrecord.username.blank?record.username=record.emailendendend

2.1. Registering Callbacks to Fire on Life Cycle Events

Callbacks can also be registered to only fire on certain life cycle events, thiscan be done using the:on option and allows complete control over when and inwhat context your callbacks are triggered.

A context is like a category or a scenario in which you want certainvalidations to apply. When you validate an ActiveRecord model, you can specify acontext to group validations. This allows you to have different sets ofvalidations that apply in different situations. In Rails, there are certaindefault contexts for validations like :create, :update, and :save.

classUser<ApplicationRecordvalidates:username,:email,presence:truebefore_validation:ensure_username_has_value,on: :create# :on takes an array as wellafter_validation:set_location,on:[:create,:update]privatedefensure_username_has_valueifusername.blank?self.username=emailendenddefset_locationself.location=LocationService.query(self)endend

It is considered good practice to declare callback methods as private. Ifleft public, they can be called from outside of the model and violate theprinciple of object encapsulation.

Refrain from using methods likeupdate,save, or any other methodsthat cause side effects on the object within your callback methods.

For instance, avoid callingupdate(attribute: "value") inside a callback. Thispractice can modify the model's state and potentially lead to unforeseen sideeffects during commit.

Instead, you can assign values directly (e.g.,self.attribute = "value") inbefore_create,before_update, or earliercallbacks for a safer approach.

3. Available Callbacks

Here is a list with all the available Active Record callbacks, listedin theorder in which they will get called during the respective operations:

3.1. Creating an Object

See theafter_commit /after_rollbacksection forexamples using these two callbacks.

There are examples below that show how to use these callbacks. We've groupedthem by the operation they are associated with, and lastly show how they can beused in combination.

3.1.1. Validation Callbacks

Validation callbacks are triggered whenever the record is validated directly viathevalid?( or its aliasvalidate)orinvalid?method, or indirectly viacreate,update, orsave. They are called beforeand after the validation phase.

classUser<ApplicationRecordvalidates:name,presence:truebefore_validation:titleize_nameafter_validation:log_errorsprivatedeftitleize_nameself.name=name.downcase.titleizeifname.present?Rails.logger.info("Name titleized to#{name}")enddeflog_errorsiferrors.any?Rails.logger.error("Validation failed:#{errors.full_messages.join(', ')}")endendend
irb>user=User.new(name:"",email:"john.doe@example.com",password:"abc123456")=> #<User id: nil, email: "john.doe@example.com", created_at: nil, updated_at: nil, name: "">irb>user.valid?Name titleized toValidation failed: Name can't be blank=>false

3.1.2. Save Callbacks

Save callbacks are triggered whenever the record is persisted (i.e. "saved") tothe underlying database, via thecreate,update, orsave methods. They arecalled before, after, and around the object is saved.

classUser<ApplicationRecordbefore_save:hash_passwordaround_save:log_savingafter_save:update_cacheprivatedefhash_passwordself.password_digest=BCrypt::Password.create(password)Rails.logger.info("Password hashed for user with email:#{email}")enddeflog_savingRails.logger.info("Saving user with email:#{email}")yieldRails.logger.info("User saved with email:#{email}")enddefupdate_cacheRails.cache.write(["user_data",self],attributes)Rails.logger.info("Update Cache")endend
irb>user=User.create(name:"Jane Doe",password:"password",email:"jane.doe@example.com")Password hashed for user with email: jane.doe@example.comSaving user with email: jane.doe@example.comUser saved with email: jane.doe@example.comUpdate Cache=> #<User id: 1, email: "jane.doe@example.com", created_at: "2024-03-20 16:02:43.685500000 +0000", updated_at: "2024-03-20 16:02:43.685500000 +0000", name: "Jane Doe">

3.1.3. Create Callbacks

Create callbacks are triggered whenever the record is persisted (i.e. "saved")to the underlying databasefor the first time — in other words, when we'resaving a new record, via thecreate orsave methods. They are called before,after and around the object is created.

classUser<ApplicationRecordbefore_create:set_default_rolearound_create:log_creationafter_create:send_welcome_emailprivatedefset_default_roleself.role="user"Rails.logger.info("User role set to default: user")enddeflog_creationRails.logger.info("Creating user with email:#{email}")yieldRails.logger.info("User created with email:#{email}")enddefsend_welcome_emailUserMailer.welcome_email(self).deliver_laterRails.logger.info("User welcome email sent to:#{email}")endend
irb>user=User.create(name:"John Doe",email:"john.doe@example.com")User role set to default: userCreating user with email: john.doe@example.comUser created with email: john.doe@example.comUser welcome email sent to: john.doe@example.com=> #<User id: 10, email: "john.doe@example.com", created_at: "2024-03-20 16:19:52.405195000 +0000", updated_at: "2024-03-20 16:19:52.405195000 +0000", name: "John Doe">

3.2. Updating an Object

Update callbacks are triggered whenever anexisting record is persisted(i.e. "saved") to the underlying database. They are called before, after andaround the object is updated.

Theafter_save callback is triggered on both create and updateoperations. However, it consistently executes after the more specific callbacksafter_create andafter_update, regardless of the sequence in which the macrocalls were made. Similarly, before and around save callbacks follow the samerule:before_save runs before create/update, andaround_save runs aroundcreate/update operations. It's important to note that save callbacks will alwaysrun before/around/after the more specific create/update callbacks.

We've already coveredvalidation andsave callbacks. See theafter_commit /after_rollback section for examples usingthese two callbacks.

3.2.1. Update Callbacks

classUser<ApplicationRecordbefore_update:check_role_changearound_update:log_updatingafter_update:send_update_emailprivatedefcheck_role_changeifrole_changed?Rails.logger.info("User role changed to#{role}")endenddeflog_updatingRails.logger.info("Updating user with email:#{email}")yieldRails.logger.info("User updated with email:#{email}")enddefsend_update_emailUserMailer.update_email(self).deliver_laterRails.logger.info("Update email sent to:#{email}")endend
irb>user=User.find(1)=>#<Userid:1,email:"john.doe@example.com",created_at:"2024-03-20 16:19:52.405195000 +0000",updated_at:"2024-03-20 16:19:52.405195000 +0000",name:"John Doe",role:"user">irb>user.update(role:"admin")User role changed to adminUpdating user with email: john.doe@example.comUser updated with email: john.doe@example.comUpdate email sent to: john.doe@example.com

3.2.2. Using a Combination of Callbacks

Often, you will need to use a combination of callbacks to achieve the desiredbehavior. For example, you may want to send a confirmation email after a user iscreated, but only if the user is new and not being updated. When a user isupdated, you may want to notify an admin if critical information is changed. Inthis case, you can useafter_create andafter_update callbacks together.

classUser<ApplicationRecordafter_create:send_confirmation_emailafter_update:notify_admin_if_critical_info_updatedprivatedefsend_confirmation_emailUserMailer.confirmation_email(self).deliver_laterRails.logger.info("Confirmation email sent to:#{email}")enddefnotify_admin_if_critical_info_updatedifsaved_change_to_email?||saved_change_to_phone_number?AdminMailer.user_critical_info_updated(self).deliver_laterRails.logger.info("Notification sent to admin about critical info update for:#{email}")endendend
irb>user=User.create(name:"John Doe",email:"john.doe@example.com")Confirmation email sent to: john.doe@example.com=>#<Userid:1,email:"john.doe@example.com",...>irb>user.update(email:"john.doe.new@example.com")Notification sent to admin about critical info update for: john.doe.new@example.com=>true

3.3. Destroying an Object

Destroy callbacks are triggered whenever a record is destroyed, but ignored whena record is deleted. They are called before, after and around the object isdestroyed.

Findexamples for usingafter_commit /after_rollback.

3.3.1. Destroy Callbacks

classUser<ApplicationRecordbefore_destroy:check_admin_countaround_destroy:log_destroy_operationafter_destroy:notify_usersprivatedefcheck_admin_countifadmin?&&User.where(role:"admin").count==1throw:abortendRails.logger.info("Checked the admin count")enddeflog_destroy_operationRails.logger.info("About to destroy user with ID#{id}")yieldRails.logger.info("User with ID#{id} destroyed successfully")enddefnotify_usersUserMailer.deletion_email(self).deliver_laterRails.logger.info("Notification sent to other users about user deletion")endend
irb>user=User.find(1)=> #<User id: 1, email: "john.doe@example.com", created_at: "2024-03-20 16:19:52.405195000 +0000", updated_at: "2024-03-20 16:19:52.405195000 +0000", name: "John Doe", role: "admin">irb>user.destroyChecked the admin countAbout to destroy user with ID 1User with ID 1 destroyed successfullyNotification sent to other users about user deletion

3.4.after_initialize andafter_find

Whenever an Active Record object is instantiated, either by directly usingnewor when a record is loaded from the database, theafter_initializecallback will be called. It can be useful to avoid the need to directly overrideyour Active Recordinitialize method.

When loading a record from the database theafter_find callback will becalled.after_find is called beforeafter_initialize if both are defined.

Theafter_initialize andafter_find callbacks have nobefore_*counterparts.

They can be registered just like the other Active Record callbacks.

classUser<ApplicationRecordafter_initializedo|user|Rails.logger.info("You have initialized an object!")endafter_finddo|user|Rails.logger.info("You have found an object!")endend
irb>User.newYou have initialized an object!=>#<Userid:nil>irb>User.firstYou have found an object!You have initialized an object!=>#<Userid:1>

3.5.after_touch

Theafter_touch callback will be called whenever an Active Record objectis touched. You canread more abouttouch in the APIdocs.

classUser<ApplicationRecordafter_touchdo|user|Rails.logger.info("You have touched an object")endend
irb>user=User.create(name:"Kuldeep")=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">irb>user.touchYou have touched an object=>true

It can be used along withbelongs_to:

classBook<ApplicationRecordbelongs_to:library,touch:trueafter_touchdoRails.logger.info("A Book was touched")endendclassLibrary<ApplicationRecordhas_many:booksafter_touch:log_when_books_or_library_touchedprivatedeflog_when_books_or_library_touchedRails.logger.info("Book/Library was touched")endend
irb>book=Book.last=> #<Book id: 1, library_id: 1, created_at: "2013-11-25 17:04:22", updated_at: "2013-11-25 17:05:05">irb>book.touch# triggers book.library.touchA Book was touchedBook/Library was touched=>true

4. Running Callbacks

The following methods trigger callbacks:

  • create
  • create!
  • destroy
  • destroy!
  • destroy_all
  • destroy_by
  • save
  • save!
  • save(validate: false)
  • save!(validate: false)
  • toggle!
  • touch
  • update_attribute
  • update_attribute!
  • update
  • update!
  • valid?
  • validate

Additionally, theafter_find callback is triggered by the following findermethods:

  • all
  • first
  • find
  • find_by
  • find_by!
  • find_by_*
  • find_by_*!
  • find_by_sql
  • last
  • sole
  • take

Theafter_initialize callback is triggered every time a new object of theclass is initialized.

Thefind_by_* andfind_by_*! methods are dynamic finders generatedautomatically for every attribute. Learn more about them in theDynamic finderssection.

5. Conditional Callbacks

As withvalidations, we can also make thecalling of a callback method conditional on the satisfaction of a givenpredicate. We can do this using the:if and:unless options, which can takea symbol, aProc or anArray.

You may use the:if option when you want to specify under which conditions thecallbackshould be called. If you want to specify the conditions under whichthe callbackshould not be called, then you may use the:unless option.

5.1. Using:if and:unless with aSymbol

You can associate the:if and:unless options with a symbol corresponding tothe name of a predicate method that will get called right before the callback.

When using the:if option, the callbackwon't be executed if the predicatemethod returnsfalse; when using the:unless option, the callbackwon't be executed if the predicate method returnstrue. This is the mostcommon option.

classOrder<ApplicationRecordbefore_save:normalize_card_number,if: :paid_with_card?end

Using this form of registration it is also possible to register severaldifferent predicates that should be called to check if the callback should beexecuted. We will cover this in theMultiple Callback Conditionssection.

5.2. Using:if and:unless with aProc

It is possible to associate:if and:unless with aProc object. Thisoption is best suited when writing short validation methods, usually one-liners:

classOrder<ApplicationRecordbefore_save:normalize_card_number,if:->(order){order.paid_with_card?}end

Since the proc is evaluated in the context of the object, it is also possible towrite this as:

classOrder<ApplicationRecordbefore_save:normalize_card_number,if:->{paid_with_card?}end

5.3. Multiple Callback Conditions

The:if and:unless options also accept an array of procs or method names assymbols:

classComment<ApplicationRecordbefore_save:filter_content,if:[:subject_to_parental_control?,:untrusted_author?]end

You can easily include a proc in the list of conditions:

classComment<ApplicationRecordbefore_save:filter_content,if:[:subject_to_parental_control?,->{untrusted_author?}]end

5.4. Using Both:if and:unless

Callbacks can mix both:if and:unless in the same declaration:

classComment<ApplicationRecordbefore_save:filter_content,if:->{forum.parental_control?},unless:->{author.trusted?}end

The callback only runs when all the:if conditions and none of the:unlessconditions are evaluated totrue.

6. Skipping Callbacks

Just as withvalidations, it is also possibleto skip callbacks by using the following methods:

Let's consider aUser model where thebefore_save callback logs any changesto the user's email address:

classUser<ApplicationRecordbefore_save:log_email_changeprivatedeflog_email_changeifemail_changed?Rails.logger.info("Email changed from#{email_was} to#{email}")endendend

Now, suppose there's a scenario where you want to update the user's emailaddress without triggering thebefore_save callback to log the email change.You can use theupdate_columns method for this purpose:

irb>user=User.find(1)irb>user.update_columns(email:'new_email@example.com')

The above will update the user's email address without triggering thebefore_save callback.

These methods should be used with caution because there may beimportant business rules and application logic in callbacks that you do not wantto bypass. Bypassing them without understanding the potential implications maylead to invalid data.

7. Suppressing Saving

In certain scenarios, you may need to temporarily prevent records from beingsaved within your callbacks.This can be useful if you have a record with complex nested associations and wantto skip saving specific records during certain operations without permanently disablingthe callbacks or introducing complex conditional logic.

Rails provides a mechanism to prevent saving records using theActiveRecord::Suppressor module.By using this module, you can wrap a block of code where you want to avoidsaving records of a specific type that otherwise would be saved by the code block.

Let's consider a scenario where a user has many notifications.Creating aUser will automatically create aNotification record as well.

classUser<ApplicationRecordhas_many:notificationsafter_create:create_welcome_notificationdefcreate_welcome_notificationnotifications.create(event:"sign_up")endendclassNotification<ApplicationRecordbelongs_to:userend

To create a user without creating a notification, we can use theActiveRecord::Suppressor module as follows:

Notification.suppressdoUser.create(name:"Jane",email:"jane@example.com")end

In the above code, theNotification.suppress block ensures that theNotification is not saved during the creation of the "Jane" user.

Using the Active Record Suppressor can introduce complexity andunexpected behavior. Suppressing saving can obscure the intended flow of yourapplication, leading to difficulties in understanding and maintaining thecodebase over time. Carefully consider the implications of using the suppressor,ensuring thorough documentation and thoughtful testing to mitigaterisks of unintended side effects and test failures.

8. Halting Execution

As you start registering new callbacks for your models, they will be queued forexecution. This queue will include all of your model's validations, theregistered callbacks, and the database operation to be executed.

The whole callback chain is wrapped in a transaction. If any callback raises anexception, the execution chain gets halted and arollback is issued, and theerror will be re-raised.

classProduct<ActiveRecord::Basebefore_validationdoraise"Price can't be negative"iftotal_price<0endendProduct.create# raises "Price can't be negative"

This unexpectedly breaks code that does not expect methods likecreate andsave to raise exceptions.

If an exception occurs during the callback chain, Rails will re-raise itunless it is anActiveRecord::Rollback orActiveRecord::RecordInvalidexception. Instead, you should usethrow :abort to intentionally halt thechain. If any callback throws:abort, the process will be aborted andcreatewill return false.

classProduct<ActiveRecord::Basebefore_validationdothrow:abortiftotal_price<0endendProduct.create# => false

However, it will raise anActiveRecord::RecordNotSaved when callingcreate!.This exception indicates that the record was not saved due to the callback'sinterruption.

User.create!# => raises an ActiveRecord::RecordNotSaved

Whenthrow :abort is called in any destroy callback,destroy will returnfalse:

classUser<ActiveRecord::Basebefore_destroydothrow:abortifstill_active?endendUser.first.destroy# => false

However, it will raise anActiveRecord::RecordNotDestroyed when callingdestroy!.

User.first.destroy!# => raises an ActiveRecord::RecordNotDestroyed

9. Association Callbacks

Association callbacks are similar to normal callbacks, but they are triggered byevents in the life cycle of the associated collection. There are four availableassociation callbacks:

  • before_add
  • after_add
  • before_remove
  • after_remove

You can define association callbacks by adding options to the association.

Suppose you have an example where an author can have many books. However, beforeadding a book to the authors collection, you want to ensure that the author hasnot reached their book limit. You can do this by adding abefore_add callbackto check the limit.

classAuthor<ApplicationRecordhas_many:books,before_add: :check_limitprivatedefcheck_limit(_book)ifbooks.count>=5errors.add(:base,"Cannot add more than 5 books for this author")throw(:abort)endendend

If abefore_add callback throws:abort, the object does not get added to thecollection.

At times you may want to perform multiple actions on the associated object. Inthis case, you can stack callbacks on a single event by passing them as anarray. Additionally, Rails passes the object being added or removed to thecallback for you to use.

classAuthor<ApplicationRecordhas_many:books,before_add:[:check_limit,:calculate_shipping_charges]defcheck_limit(_book)ifbooks.count>=5errors.add(:base,"Cannot add more than 5 books for this author")throw(:abort)endenddefcalculate_shipping_charges(book)weight_in_pounds=book.weight_in_pounds||1shipping_charges=weight_in_pounds*2shipping_chargesendend

Similarly, if abefore_remove callback throws:abort, the object does notget removed from the collection.

These callbacks are called only when the associated objects are added orremoved through the association collection.

# Triggers `before_add` callbackauthor.books<<bookauthor.books=[book,book2]# Does not trigger the `before_add` callbackbook.update(author_id:1)

10. Cascading Association Callbacks

Callbacks can be performed when associated objects are changed. They workthrough the model associations whereby life cycle events can cascade onassociations and fire callbacks.

Suppose an example where a user has many articles. A user's articles should bedestroyed if the user is destroyed. Let's add anafter_destroy callback to theUser model by way of its association to theArticle model:

classUser<ApplicationRecordhas_many:articles,dependent: :destroyendclassArticle<ApplicationRecordafter_destroy:log_destroy_actiondeflog_destroy_actionRails.logger.info("Article destroyed")endend
irb>user=User.first=>#<Userid:1>irb>user.articles.create!=>#<Articleid:1,user_id:1>irb>user.destroyArticle destroyed=>#<Userid:1>

When using abefore_destroy callback, it should be placed beforedependent: :destroy associations (or use theprepend: true option), toensure they execute before the records are deleted bydependent: :destroy.

11. Transaction Callbacks

11.1.after_commit andafter_rollback

Two additional callbacks are triggered by the completion of a databasetransaction:after_commit andafter_rollback. These callbacks arevery similar to theafter_save callback except that they don't execute untilafter database changes have either been committed or rolled back. They are mostuseful when your Active Record models need to interact with external systemsthat are not part of the database transaction.

Consider aPictureFile model that needs to delete a file after thecorresponding record is destroyed.

classPictureFile<ApplicationRecordafter_destroy:delete_picture_file_from_diskdefdelete_picture_file_from_diskifFile.exist?(filepath)File.delete(filepath)endendend

If anything raises an exception after theafter_destroy callback is called andthe transaction rolls back, then the file will have been deleted and the modelwill be left in an inconsistent state. For example, suppose thatpicture_file_2 in the code below is not valid and thesave! method raises anerror.

PictureFile.transactiondopicture_file_1.destroypicture_file_2.save!end

By using theafter_commit callback we can account for this case.

classPictureFile<ApplicationRecordafter_commit:delete_picture_file_from_disk,on: :destroydefdelete_picture_file_from_diskifFile.exist?(filepath)File.delete(filepath)endendend

The:on option specifies when a callback will be fired. If you don'tsupply the:on option the callback will fire for every life cycle event.Readmore about:on.

When a transaction completes, theafter_commit orafter_rollback callbacksare called for all models created, updated, or destroyed within thattransaction. However, if an exception is raised within one of these callbacks,the exception will bubble up and any remainingafter_commit orafter_rollback methods willnot be executed.

classUser<ActiveRecord::Baseafter_commit{raise"Intentional Error"}after_commit{# This won't get called because the previous after_commit raises an exceptionRails.logger.info("This will not be logged")}end

If your callback code raises an exception, you'll need to rescue it andhandle it within the callback in order to allow other callbacks to run.

after_commit makes very different guarantees thanafter_save,after_update, andafter_destroy. For example, if an exception occurs in anafter_save the transaction will be rolled back and the data will not bepersisted.

classUser<ActiveRecord::Baseafter_savedo# If this fails the user won't be saved.EventLog.create!(event:"user_saved")endend

However, duringafter_commit the data was already persisted to the database,and thus any exception won't roll anything back anymore.

classUser<ActiveRecord::Baseafter_commitdo# If this fails the user was already saved.EventLog.create!(event:"user_saved")endend

The code executed withinafter_commit orafter_rollback callbacks is itselfnot enclosed within a transaction.

In the context of a single transaction, if you represent the same record in thedatabase, there's a crucial behavior in theafter_commit andafter_rollbackcallbacks to note. These callbacks are triggered only for the first object ofthe specific record that changes within the transaction. Other loaded objects,despite representing the same database record, will not have their respectiveafter_commit orafter_rollback callbacks triggered.

classUser<ApplicationRecordafter_commit:log_user_saved_to_db,on: :updateprivatedeflog_user_saved_to_dbRails.logger.info("User was saved to database")endend
irb>user=User.createirb>User.transaction{user.save;user.save}# User was saved to database

This nuanced behavior is particularly impactful in scenarios where youexpect independent callback execution for each object associated with the samedatabase record. It can influence the flow and predictability of callbacksequences, leading to potential inconsistencies in application logic followingthe transaction.

11.2. Aliases forafter_commit

Using theafter_commit callback only on create, update, or delete is common.Sometimes you may also want to use a single callback for bothcreate andupdate. Here are some common aliases for these operations:

Let's go through some examples:

Instead of usingafter_commit with theon option for a destroy like below:

classPictureFile<ApplicationRecordafter_commit:delete_picture_file_from_disk,on: :destroydefdelete_picture_file_from_diskifFile.exist?(filepath)File.delete(filepath)endendend

You can instead use theafter_destroy_commit.

classPictureFile<ApplicationRecordafter_destroy_commit:delete_picture_file_from_diskdefdelete_picture_file_from_diskifFile.exist?(filepath)File.delete(filepath)endendend

The same applies forafter_create_commit andafter_update_commit.

However, if you use theafter_create_commit and theafter_update_commitcallback with the same method name, it will only allow the last callback definedto take effect, as they both internally alias toafter_commit which overridespreviously defined callbacks with the same method name.

classUser<ApplicationRecordafter_create_commit:log_user_saved_to_dbafter_update_commit:log_user_saved_to_dbprivatedeflog_user_saved_to_db# This only gets called onceRails.logger.info("User was saved to database")endend
irb>user=User.create# prints nothingirb>user.save# updating @userUser was saved to database

In this case, it's better to useafter_save_commit instead which is an aliasfor using theafter_commit callback for both create and update:

classUser<ApplicationRecordafter_save_commit:log_user_saved_to_dbprivatedeflog_user_saved_to_dbRails.logger.info("User was saved to database")endend
irb>user=User.create# creating a UserUser was saved to databaseirb>user.save# updating userUser was saved to database

11.3. Transactional Callback Ordering

By default (from Rails 7.1), transaction callbacks will run in the order theyare defined.

classUser<ActiveRecord::Baseafter_commit{Rails.logger.info("this gets called first")}after_commit{Rails.logger.info("this gets called second")}end

However, in prior versions of Rails, when defining multiple transactionalafter_ callbacks (after_commit,after_rollback, etc), the order in whichthe callbacks were run was reversed.

If for some reason you'd still like them to run in reverse, you can set thefollowing configuration tofalse. The callbacks will then run in the reverseorder. See theActive Record configurationoptionsfor more details.

config.active_record.run_after_transaction_callbacks_in_order_defined=false

This applies to allafter_*_commit variations too, such asafter_destroy_commit.

11.4. Per transaction callback

You can also register transactional callbacks such asbefore_commit,after_commit andafter_rollback on a specific transaction.This is handy in situations where you need to perform an action that isn't specific to a model but rather a unit of work.

ActiveRecord::Base.transaction yields anActiveRecord::Transaction object, which allows registering the said callbacks on it.

Article.transactiondo|transaction|article.update(published:true)transaction.after_commitdoPublishNotificationMailer.with(article:article).deliver_laterendend

11.5.ActiveRecord.after_all_transactions_commit

ActiveRecord.after_all_transactions_commit is a callback that allows you to run code after all the current transactions have been successfully committed to the database.

defpublish_article(article)Article.transactiondoPost.transactiondoActiveRecord.after_all_transactions_commitdoPublishNotificationMailer.with(article:article).deliver_later# An email will be sent after the outermost transaction is committed.endendendend

A callback registered toafter_all_transactions_commit will be triggered after the outermost transaction is committed. If any of the currently open transactions is rolled back, the block is never called.In the event that there are no open transactions at the time a callback is registered, the block will be yielded immediately.

12. Callback Objects

Sometimes the callback methods that you'll write will be useful enough to bereused by other models. Active Record makes it possible to create classes thatencapsulate the callback methods, so they can be reused.

Here's an example of anafter_commit callback class to deal with the cleanupof discarded files on the filesystem. This behavior may not be unique to ourPictureFile model and we may want to share it, so it's a good idea toencapsulate this into a separate class. This will make testing that behavior andchanging it much easier.

classFileDestroyerCallbackdefafter_commit(file)ifFile.exist?(file.filepath)File.delete(file.filepath)endendend

When declared inside a class, as above, the callback methods will receive themodel object as a parameter. This will work on any model that uses the classlike so:

classPictureFile<ApplicationRecordafter_commitFileDestroyerCallback.newend

Note that we needed to instantiate a newFileDestroyerCallback object, sincewe declared our callback as an instance method. This is particularly useful ifthe callbacks make use of the state of the instantiated object. Often, however,it will make more sense to declare the callbacks as class methods:

classFileDestroyerCallbackdefself.after_commit(file)ifFile.exist?(file.filepath)File.delete(file.filepath)endendend

When the callback method is declared this way, it won't be necessary toinstantiate a newFileDestroyerCallback object in our model.

classPictureFile<ApplicationRecordafter_commitFileDestroyerCallbackend

You can declare as many callbacks as you want inside your callback objects.



Back to top
[8]ページ先頭

©2009-2025 Movatter.jp