I am trying to create a record with association. Within the create
method, I would also like to pre-populate dependent (has_many) records
from a template in the database.
The child records are mysteriously rolled back if I insert
them in a loop. If I try to insert a single child record, it works.I
have read the books and tried to google my way out of this but am at a
dead end. Any help is appreciated.
Problem Statement ------------
PrototypeModel has many Departments .
Departments may also be grouped within Departments.
Trying to create a new PrototypeModel and populating the departments
(behind the scenes) from a template PrototypeModel specified by the
user in params[:prototype_model][:parent_id].
The save of the PrototypeModel fails as the new Department records are
invalid.
I checked the instances and find that the department.id is
nil. But that id is supposed to be populated by the associated
save! If I replace the departments.build argument in the
controller::create with a set of static arguments like :name => ‘Test
name’, :description=> ‘Test Desc’ then it works. though only one
hard code department is created
Just cant get my head around this. Code is below:
Code :
- class PrototypeModel < ActiveRecord::Base
- belongs_to :author, :class_name => ‘User’
- has_many :departments
- belongs_to :prototype_model
- acts_as_tree :foreign_key => “parent_id”
- end
Code :
- class Department < ActiveRecord::Base
- validates_presence_of :name, :description
- validates_presence_of :parent_id
- acts_as_tree :foreign_key => “parent_id”
- belongs_to :department
- belongs_to :prototype_model
- end
Code :
-
POST /prototype_models
-
POST /prototype_models.xml
- def create
-
@template_model = PrototypeModel.find( params
[:prototype_model][:parent_id] )
6. template_departments = @template_model.departments
7.
8. @prototype_model = PrototypeModel.new(params
[:prototype_model])
9. @prototype_model.author = current_user
10.
11. for mydepartment in template_departments
12. logger.debug “Cloning Department #{mydepartment.name}”
13.
14. newDepartment= @prototype_model.departments.build( :name =>
mydepartment.name, :description=>
mydepartment.description, :parent_id=> mydepartment.parent_id )
15. end
16.
17. respond_to do |format|
18. if @prototype_model.save
19. flash[:notice] = ‘PrototypeModel was successfully
created.’
20. format.html { redirect_to(@prototype_model) }
21. format.xml { render :xml => @prototype_model, :status
=> :created, :location => @prototype_model }
22. else
23. format.html { render :action => “new” }
24. format.xml { render :xml =>
@prototype_model.errors, :status => :unprocessable_entity }
25. end
26. end
27. end
I am using Rails 2.2.2 and Ruby 1.8.6
thanks