17

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?

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
chell
  • 7,646
  • 16
  • 74
  • 140

1 Answers1

46

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

Dennis
  • 56,821
  • 26
  • 143
  • 139
Dmitry Maksimov
  • 2,861
  • 24
  • 19
  • 2
    the documentation details have been moved to [here](http://guides.rubyonrails.org/active_record_callbacks.html#using-if-and-unless-with-a-symbol) – gotva Sep 15 '13 at 08:03