I am using accepts_nested_attributes_for in one of my Rails models, and I want to save the children after creating the parent.
The form works fine, but the validation fails. For simplicity, imagine the following:
class Project < ActiveRecord::Base has_many :tasks accepts_nested_attributes_for :tasks end class Task < ActiveRecord::Base belongs_to :project validates_presence_of :project_id validates_associated :project end
And I run:
Project.create!( :name => 'Something', :task_attributes => [ { :name => '123' }, { :name => '456' } ] )
When saving the project model, verification is not performed in tasks because they do not have project_id (since the project was not saved).
Rails seems to execute the following pattern:
- Check project
- Confirm Tasks
- Save project
- Save Tasks
The sample should be:
- Check project
- On Pass: Save the project and continue ...
- Confirm Tasks
- On Pass: Save Tasks
- In case of failure: delete the project (possibly rollback)
So my question boils down to the following: How can I get Rails to run the project_id = (or project =) method and check for the child elements (tasks) AFTER the parent (project) was saved, but NOT saving the parent (project), if any child (task) is invalid?
Any ideas?
validation ruby-on-rails activerecord nested
Ryan Townsend Jun 01 '09 at 16:43 2009-06-01 16:43
source share