When I submit this form, it is creating 2 identical records in the Members table (the fields_for part of the form). Please help me understand why that is happening.
The basic setup is: a Comp has many Teams and a Team has many Members. When creating a new Team, the first Member created should be the team’s secretary (which means the secretary_flag field in the Members table should be set to TRUE.) This form below is supposed to create a new Team, create the first team member, and mark that team member as the secretary.
The controller:
def new
@comp = Comp.find(params[:comp_id])
@team = @comp.teams.new
@team.members.build
end
def create
@comp = Comp.find(params[:comp_id])
@team = @comp.teams.create(params[:team])
if @team.update_attributes(params[:team])
flash[:success] = "Team added successfully."
redirect_to new_comp_team_member_path(@comp,@team)
else
render 'new'
end
end
The form view:
<%= form_for [@comp,@team] do |builder| %>
<%= builder.label :team_name, "Team name" %>
<%= builder.text_field :team_name %>
<%= builder.fields_for :members do |f| %>
<%= f.label :member_email, "Email address of team secretary" %>
<%= f.text_field :member_email %>
<%= f.hidden_field :secretary_flag, :value => 1 %>
<% end %>
<%= builder.submit "Create new team" %>
<% end %>
And in my routes:
resources :comps do
resources :teams do
resources :members
end
end
And in my models:
comp.rb:
attr_accessible :teams_attributes
has_many :teams, :dependent => :destroy
accepts_nested_attributes_for :teams, :allow_destroy => :true
team.rb:
attr_accessible :members_attributes
belongs_to :comp
has_many :members
accepts_nested_attributes_for :members
member.rb:
belongs_to :team
The solution I figured out was very basic. In my create action I accidentally put:
when it should have been:
I still don’t understand why that would have created 2 identical records though, but it now works.