Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use after_create with a condition in the model

I have a method that is called after the creation of an object

after_create :send_welcome_email

Is there a way to limit this to a condition, such as the value of an attribute of an object

after_create :send_welcome_email unless self.role == "Celebrant"

for example?

like image 952
chell Avatar asked Sep 06 '11 02:09

chell


1 Answers

There are three ways to do this: Symbol, String, or Proc.

class User < ActiveRecord::Base

  after_create :send_welcome_email, unless: :is_celebrant?
  after_create :send_welcome_email, unless: "is_celebrant?"
  after_create :send_welcome_email, unless: Proc.new { self.role == "Celebrant" }

end

Documentation

like image 102
Dmitry Maksimov Avatar answered Oct 05 '22 23:10

Dmitry Maksimov