【问题标题】:ensure association is created or saved after primary model has been saved and created Rails 4确保在保存和创建主要模型之后创建或保存关联 Rails 4
【发布时间】: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


【解决方案1】:

可能有。可能您还可以在之前发生的应用程序模型上使用另一个回调,它们有很多。见Active Record Callbacks

然而事实就是如此,其他人称之为rails callback hell

这里的最佳做法是创建一个表单对象,它按照您需要的顺序创建数据并删除回调

class ApplicationCommitmentForm
  include ActiveModel::Model


  attr_accessor ...

  def submit
    a = Application.create ..
    a.update_case_code
    a.commitments.create ...
  end


end

ActiveModel Form Objects

顺便说一句,您还可以将提交代码包装到事务中,以确保创建所有记录或在任何错误的情况下什么都没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多