Nested objects with Formtastic

Published 16 March 2010

After several hours beating my head against a desk trying to get my nested Formtastic form working, I figured out the reason.\r\n\r\nAssuming you have a simple Rails one-to-many relationship:\r\n\r\n@@@ ruby\r\nclass Candidate < ActiveRecord::Base\r\n has_many :jobs\r\nend\r\n\r\nclass Job < ActiveRecord::Base\r\n belongs_to :candidate\r\nend\r\n@@@\r\n\r\nand you have a form which can update our candidate and up to 3 jobs at the same time, so we prepare that in our controller:\r\n\r\n@@@ ruby\r\nclass CandidatesController < ApplicationController\r\n def new\r\n candidate = Candidate.new\r\n 3.times do\r\n @candidate.jobs.build\r\n end\r\n end\r\nend\r\n@\r\n\r\nso the form allows creation of the candidate and 3 jobs too:\r\n\r\n@ruby\r\n<% semantic_form_for @candidate do |f| %>\r\n <%= f.inputs %>\r\n <%= f.inputs :for => :jobs do |j| %>\r\n <%= j.input :name %>\r\n <% end %>\r\n<% end %>\r\n@\r\n\r\nbut for some reason this just didn't work.\r\n\r\nThe jobs input displayed only once and _j.object_ was nil.\r\n\r\nAfter some searching and head scratching I finally figured this out, which isn't mentioned on the Formtastic site. You need to use *accepts_nested_attributes_for*.\r\n\r\nSo the model will look like this:\r\n\r\n@ ruby\r\nclass Candidate < ActiveRecord::Base\r\n has_many :jobs\r\n accepts_nested_attributes_for :jobs\r\nend\r\n\r\nclass Job < ActiveRecord::Base\r\n belongs_to :candidate\r\nend\r\n@@\r\n\r\nAnd then it works!