我有两个模型,一个属于另一个,似乎无法让它们正确保存。问题源于这样一个事实,当我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
这是孩子:
# 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
保存将失败,引用“广告执行:执行宏不能为空白”。
感觉这不应该那么难。我错过了什么?