如何在模型中使用after_create和条件 [英] How should I use after_create with a condition in the model

查看:198
本文介绍了如何在模型中使用after_create和条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在创建对象后调用的方法

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"

例如?

推荐答案

有三种方法可以做到这一点:Symbol,String或Proc.

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

文档

这篇关于如何在模型中使用after_create和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆