【问题标题】:Rails4: Access child object in parent while creating parent from child formRails4:从子窗体创建父级时访问父级中的子对象
【发布时间】:2015-04-18 18:13:22
【问题描述】:

我有关联

交付模式

class Delivery < ActiveRecord::Base
  belongs_to :schedule, inverse_of: :deliveries
  accepts_nested_attributes_for :schedule
end

调度模型

class Schedule < ActiveRecord::Base
  has_many :deliveries, inverse_of: :schedule
  include PushUpdates

  def offer
    deliveries.last.try(:offer)
  end
end

PushUpdates:app/model/concerns/push_updates.rb

module PushUpdates
  extend ActiveSupport::Concern

  included do
    after_create {update_client_store :create unless Rails.env.test? }
    after_update {update_client_store :update unless Rails.env.test? }
  end

  def update_client_store(operation)
    ...
    self.offer
  end
end

现在,在保存交付的同时,我还接受了一组时间表详细信息。

当它保存交付和计划时,会为计划模型调用after_create 回调,当它试图找出deliveries.last 时,它会给出nil 值。 由于我接受它作为嵌套属性的一部分,因此交付对象应该可供它使用,但它仍然提供 nil 值。

我在这里遗漏了什么吗?谢谢。

【问题讨论】:

    标签: ruby-on-rails-4 activerecord ruby-on-rails-3.2 associations rails-activerecord


    【解决方案1】:

    在我看来,Rails 正在尝试在关联记录提交之前进行数据库调用。

    还有一个额外的回调,您可以查看after_commit(代替after_create,一旦记录提交到您使用的任何数据库,就会触发该回调。

    这应该意味着您的deliveries.last 应该返回非空。您也可以使用 self.reload 强制对模型进行数据库查找,尽管这可能会导致意外行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多