このフォームを送信すると、Members テーブル (フォームの fields_for 部分) に 2 つの同一のレコードが作成されます。なぜそれが起こっているのかを理解するのを手伝ってください。
基本的なセットアップは次のとおりです。コンプには多くのチームがあり、チームには多くのメンバーがいます。新しいチームを作成する場合、作成される最初のメンバーはチームの秘書である必要があります (つまり、メンバー テーブルの secretary_flag フィールドを TRUE に設定する必要があります)。以下のフォームは、新しいチームを作成し、最初のチーム メンバーを作成し、そのチーム メンバーを秘書としてマークします。
コントローラー:
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
フォーム ビュー:
<%= 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 %>
そして私のルートでは:
resources :comps do
resources :teams do
resources :members
end
end
そして私のモデルでは:
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
メンバー.rb:
belongs_to :team