Ruby on rails Rails:one是否属于未正确建立关系

Ruby on rails Rails:one是否属于未正确建立关系,ruby-on-rails,nested-attributes,one-to-one,Ruby On Rails,Nested Attributes,One To One,我有两个模型,一个属于另一个,似乎无法让它们正确保存。问题源于这样一个事实:当我在模型上使用build方法时,它没有在内存中相互分配它们,因此当我尝试在父对象上调用.save时,子对象没有设置父对象的ID,并且失败 以下是父模型: # id int(11) # execution_id int(11) # macro_type_id int(11) # macro_key_id int(11) # created_at datetime #

我有两个模型,一个属于另一个,似乎无法让它们正确保存。问题源于这样一个事实:当我在模型上使用
build
方法时,它没有在内存中相互分配它们,因此当我尝试在父对象上调用
.save
时,子对象没有设置父对象的ID,并且失败

以下是父模型:

#  id             int(11)
#  execution_id   int(11)
#  macro_type_id  int(11)
#  macro_key_id   int(11)
#  created_at     datetime
#  updated_at     datetime

class ExecutionMacro < ActiveRecord::Base
  belongs_to :execution
  belongs_to :macro_type
  belongs_to :macro_key
  has_one :advertisement_execution, :dependent => :destroy
  accepts_nested_attributes_for :advertisement_execution

  attr_accessible :macro_key_id, :macro_type_id, :advertisement_execution_attributes

  validates :execution, :presence => true
  validates :macro_type, :presence => true
  validates :macro_key, :presence => true
end
保存将失败,引用“广告执行:执行宏不能为空”


我觉得这没那么难。我遗漏了什么?

诀窍在于调用build\u advertization\u execution时@em不会保存到数据库中。在本例中,@em.id和@ae.id等于nil(因为它们没有持久化),这就是为什么@ae.execution\u macro\u id和@em.advision\u execution\u id也设置为nil的原因。
我的建议是重新考虑验证逻辑,或者在创建广告执行(请参见.save(validate:false))之前,在不进行验证的情况下保存执行宏。

诀窍在于调用build\u advertization\u execution时@em不会保存到数据库中。在本例中,@em.id和@ae.id等于nil(因为它们没有持久化),这就是为什么@ae.execution\u macro\u id和@em.advision\u execution\u id也设置为nil的原因。
我的建议是重新考虑验证逻辑或在创建广告执行之前保存执行宏(请参见.save(validate:false))。

尝试验证id,而不是对象。如下所示:
验证:execution\u macro\u id,:presence=>true
无骰子。这没有改变任何东西=/如果删除验证,它是否正确保存?请尝试验证id,而不是对象。如下所示:
验证:execution\u macro\u id,:presence=>true
无骰子。这没有改变任何东西=/如果删除验证,它是否正确保存?
#  id                        int(11)
#  advertisement_id          int(11)
#  execution_macro_id        int(11)
#  advertisement_version_id  int(11)
#  created_at                datetime
#  updated_at                datetime
#  deleted_at                datetime

class AdvertisementExecution < ActiveRecord::Base
  belongs_to :advertisement
  belongs_to :advertisement_version
  belongs_to :execution_macro

  attr_accessible :advertisement_id, :advertisement_version_id, :execution_macro_id

  validates :execution_macro, :presence => true
  validates :advertisement, :presence => true
  validates :advertisement_version, :presence => true
end
@execution = Execution.find(1)
@em = @execution.execution_macros.build(:macro_type_id => 1, :macro_key_id => 1)
@ae = @em.build_advertisement_execution(:advertisement_id => 1, :advertisement_version_id => 1)
if @em.save
  "do something"
else
  "throw an error"
end