Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
Rails: call same method in after_commit for create, update, delete but do separate things based on certain flags

I want to create and delete the user on a 3rd party service based on the below scenarios

  1. create user on 3rd party

    • when user is created in the application
    • marked as active from inactive (i have a column on my User model called is_active)
  2. delete user on 3rd party

    • when user is deleted from the application
    • marked as inactive

looks like I can make use of the after_commit callback, but how do I identify in the after_commit that action is create, update or delete

Any help on this will be helpful.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Don't use a callbacks for this -- you are going to regret it.
The main problem with callbacks are:

  • No context -- you don't actually have any idea what's going on in the app.
  • Its hard to control when the callback actually fires -- and more importantly when you don't want it to fire (like for example when loading fixtures).
  • It puts too much responsibility on the model.
  • You can't test the callback logic in isolation from creating/updating/destroying the record.

I really can't understate this when you seem to be dealing with a third party API as well. Using an implicit mechanism like callbacks when you're touching the application boundary is a really bad idea. The whole idea of piping everything through a single method is also not sound.

Instead you can use patterns such as service objects to handle the "transformations" of the model.

class UserCreationService
  def initialize(user)
    @user = user
  end

  def perform
    # do something with @user
  end
end


class UserInactivationService
  def initialize(user)
    @user = user
  end

  def perform
    # do something with @user
  end
end

These do a single job and are easy to test and will only fire when you explicitly want them to. ActiveJob is actually an example of this pattern.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!