Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda