How should I use after_create with a condition in the model

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 15:44:40

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/7314493/how-should-i-use-after-create-with-a-condition-in-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!