ruby-on-rails - `before_create` 和 `after_create` 之间有什么区别以及何时使用哪个?

标签 ruby-on-rails ruby-on-rails-3 rails-activerecord

我知道 before_create 在对象转换到数据库之前被调用,after_create 在之后被调用。

before_create 将被调用而 after_create 而不是的唯一时间是对象未能满足数据库常量(唯一键等)。除此之外,我可以将 after_create 的所有逻辑放在 before_create 中

我错过了什么吗?

最佳答案

为了理解这两个回调,首先你需要知道这两个回调是什么时候被调用的。下面是 ActiveRecord 回调排序:

(-) 节省

(-) 有效的

(1) before_validation

(-) 证实

(2) after_validation

(3) before_save

(4) before_create

(-) 创建

(5) after_create

(6) after_save

(7) after_commit

你可以看到 before_createafter_validation 之后调用,把它放在简单的上下文中,在您的 ActiveRecord 满足验证后调用此回调。此 before_create通常用于在验证后设置一些额外的属性。

现在转到 after_create ,您可以看到这是在记录持久存储到数据库后创建的。人们通常使用它来做诸如发送通知、记录之类的事情。

对于这个问题,你应该什么时候使用它?答案是“你根本不应该使用它”。 ActiveRecord 回调是反模式的,经验丰富的 Rails 开发人员认为它是代码味道的,您可以通过使用 Service 对象来实现所有这些。这是一个简单的例子:

class Car < ActiveRecord::Base
  before_create :set_mileage_to_zero
  after_create  :send_quality_report_to_qa_team
end

can be rewritten in

# app/services/car_creation.rb

class CarCreation

  attr_reader :car

  def initialize(params = {})
    @car = Car.new(params)
    @car.mileage = 0
  end

  def create_car
    if car.save
      send_report_to_qa_team
    end 
  end

  private

  def send_report_to_qa_team
  end
end

如果你有简单的应用程序,那么回调是可以的,但是随着你的应用程序的增长,你会摸不着头脑,不确定是什么设置了这个或那个属性,测试将非常困难。

再想一想,我仍然认为您应该广泛使用回调并体验重构它的痛苦,然后您将学会避免它;) 祝你好运

关于ruby-on-rails - `before_create` 和 `after_create` 之间有什么区别以及何时使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22952664/

相关文章:

ruby-on-rails - Rails 缺少模板

ruby-on-rails - 如何将 Google Analytics 结果合并到我的 Rails 3 应用程序中?

ruby-on-rails - ActiveRecord OR 查询

ruby-on-rails - 如何在 Rails 中使用 rake 任务连接到 SQL Server?

ruby-on-rails - ActiveRecord 提取到 SQL

ruby-on-rails - 如何防止 Rails `exists?` 调用 `after_find`?

ruby-on-rails - 使用 redis-rails,如何删除 session 缓存以外的所有内容?

ruby-on-rails - Ruby:在一个文件中放置多个类是否可以接受?

ruby-on-rails - rails 3 : Simple form start date

javascript - 尽管不支持 HTML5 data-* 属性,Firefox 3 是否支持 Rails3 UJS?