Nested attributes not working creating children wi

2020-07-25 08:55发布

问题:

I have two models:

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

When, in my controller, I want to create a shift with ranges I'm getting:

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

If I remove validates :shift, presence: true from Range model this works beautifully. I'm able to create a new shift with his children. ActiveRecord does that for me.

The question is: why do I need to remove that validation to make this work?

回答1:

The thing with validating presence of parent like this is timing !! actually the Shift is not yet saved so when trying to create nested ranges it won't find parent Shift in database.

I found this workaround here

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

and i quote (with minor modifications) from the same source:

With this option rails won't try to get parent from database when child is validated. The parent will be got from memory. If you don't familiar with this option I strongly recommend you to read an official rails guide