【发布时间】:2016-11-18 08:38:52
【问题描述】:
我有这两个模型如下
class Application < ActiveRecord::Base
has_many :commitments, class_name: "Commitment", \
:source => :application, dependent: :destroy
accepts_nested_attributes_for :commitments
after_create: update_case_code
end
class Commitment < ActiveRecord::Base
belongs_to :application
after_create: send_notification
def send_notification
ap self.application.case_code
end
end
class ApplicationsController < ApplicationController
def create
@application = Application.new(params)
@application.save
end
end
每当我创建一个新的应用程序记录时,在我的 application_controller 中,也会在 Commitment 中创建一个新记录,它会尝试从应用程序记录中获取 case_code,但应用程序模型的 after_create 方法尚未执行。
有什么办法可以优化这段代码以使其正常工作吗?
【问题讨论】:
-
it tries to get the case_code from the application record but the after_create method of the application model hasnt been executed yet这是什么意思。它调用send_notification的原因是因为after_create回调已被调用。 -
Application Model 中的 after_create 仅在 Commitment 模型中的 after_create 之后执行。我希望它是另一种方式
-
正如您正确提到的,如果我理解正确的话,在
Application模型中创建记录之前,它会继续在Commitment模型中创建记录。视情况而定
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord