Using Formtastic's semantic_fields_for with a has_many association

Eric M. picture Eric M. · Sep 16, 2010 · Viewed 16k times · Source

I am trying to create a nested form using formtastic. I've included my code below but am running into some problems that I've also listed below. Any suggestions? Thanks.

# Home model
class Home < ActiveRecord::Base
  has_many :home_members
  accepts_nested_attributes_for :home_members, :reject_if => :all_blank, :update_only => true, :allow_destroy => true
end


# Form builder in members/new.html.erb
<%= semantic_form_for @home, :url => home_members_path(@home), :html => { :method => :post }, :remote => true do |f| %>
  <%= f.inputs do %>
    <%= f.semantic_fields_for :home_members do |h| %>
    <%= h.input :name %>
    <%= h.input :email %>
    <%= h.input :birthday, :as => :string %>
  <% end %>
<% end %>

# members_controller's new method; @home is set in a before filter
def new
  2.times{ @home.home_members.build }
end
  1. A default user is created when a Home is saved. How do I have the form display only the newly created records and not the existing one?

  2. If #1 isn't possible, how do I make the existing record update? I have update_only set on the accepts_nested_attributes_for, but a new record is still created.

  3. I am doing 2.times{ @home.home_members.build } in the controller action. When I print the size of @home.home_members I get 3 (one already exists) as expected. Why is the form only displaying 2 sets of inputs, one being populated with the existing home_member data?

Answer

Ingo picture Ingo · Apr 4, 2011

well to answer question 1) show only the newly created objects

# Form builder in members/new.html.erb
<%= semantic_form_for @home, :url => home_members_path(@home), :html => { :method => :post }, :remote => true do |f| %>
  <%= f.inputs do %>
    <%= f.semantic_fields_for :home_members do |h| %>
    <% if h.object.new_record? %>
      <%= h.input :name %>
      <%= h.input :email %>
      <%= h.input :birthday, :as => :string %>
    <% end %>
  <% end %>
<% end %>