嵌套属性无法使用新父级创建子级

我有两个型号:

class Shift < ActiveRecord::Base attr_accessible :ranges_attributes has_many :ranges accepts_nested_attributes_for :ranges, allow_destroy: true end class Range < ActiveRecord::Base belongs_to :shift validates :shift, presence: true end 

在我的控制器中,当我想创建一个带有范围的class次时:

 Shift.create! params[:shift] #ActiveRecord::RecordInvalid Exception: Validation failed: Shift ranges shift can't be blank 

如果我从Range模型中移除validates :shift, presence: true ,这可以很好地工作。 我能够和他的孩子一起创造一个新的转变。 ActiveRecord为我做到了这一点。

问题是: 为什么我需要删除该validation才能使其工作?

validation像这样的父母存在的事情是时间 !! 实际上Shift尚未保存,所以在尝试创建嵌套ranges它不会在数据库中找到父Shift

我在这里找到了这个解决方法

 class Shift < ActiveRecord::Base attr_accessible :ranges_attributes has_many :ranges, :inverse_of => :shift accepts_nested_attributes_for :ranges, allow_destroy: true end 

我从相同的来源引用(稍作修改):

使用此选项时,rails将不会尝试在validation子级时从数据库中获取父级。 父母将从记忆中获得。 如果您不熟悉此选项,我强烈建议您阅读官方的rails指南