質問

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?

役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top