After several hours beating my head against a desk trying to get my nested Formtastic form working, I figured out the reason.
Assuming you have a simple Rails one-to-many relationship:
class Candidate < ActiveRecord::Base has_many :jobs end class Job < ActiveRecord::Base belongs_to :candidate end
and 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:
class CandidatesController < ApplicationController def new @candidate = Candidate.new 3.times do @candidate.jobs.build end end end
so the form allows creation of the candidate and 3 jobs too:
<% semantic_form_for @candidate do |f| %> <%= f.inputs %> <%= f.inputs :for => :jobs do |j| %> <%= j.input :name %> <% end %> <% end %>
but for some reason this just didn’t work.
The jobs input displayed only once and j.object was nil.
After 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.
So the model will look like this:
class Candidate < ActiveRecord::Base has_many :jobs accepts_nested_attributes_for :jobs end class Job < ActiveRecord::Base belongs_to :candidate end
And then it works!