accepts_nested_attributes_for child association validation failing accepts_nested_attributes_for child association validation failing ruby-on-rails ruby-on-rails

accepts_nested_attributes_for child association validation failing


Use :inverse_of and validates_presence_of :parent. This should fix your validation problem.

   class Dungeon < ActiveRecord::Base     has_many :traps, :inverse_of => :dungeon   end   class Trap < ActiveRecord::Base     belongs_to :dungeon, :inverse_of => :traps     validates_presence_of :dungeon   end

http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_presence_of

https://github.com/rails/rails/blob/73f2d37505025a446bb5314a090f412d0fceb8ca/activerecord/test/cases/nested_attributes_test.rb


Use this answer for Rails 2, otherwise see below for the :inverse_of answer

You can work around this by not checking for the project_id if the associated project is valid.

class Task < ActiveRecord::Base  belongs_to :project  validates_presence_of :project_id, :unless => lambda {|task| task.project.try(:valid?)}  validates_associated :projectend


Only validate the relationship, not the ID:

class Task < ActiveRecord::Base  belongs_to :project  validates_presence_of :projectend

As soon as the association is populated, ActiveRecord will consider the validation to have succeeded, whether or not the model is saved. You might want to investigate autosaving as well, to ensure the task's project is always saved:

class Task < ActiveRecord::Base  belongs_to :project, :autosave => true  validates_presence_of :projectend