Why does my database only contain entries for the first player? It successfully saves all rounds for the first player but not for 2-6. Any ideas?
Game Controller def create @game = Game.new(params[:game])
if @game.save @opponent.games << @game 5.times { @game.rounds.create } ... end
def update params[:game][:existing_round_attributes] ||= {} @game = Game.find(params[:id])
if @game.update_attributes(params[:game]) .... end
Game Model def new_round_attributes=(round_attributes) round_attributes.each do |attributes| rounds.build(attributes) end end
def existing_round_attributes=(round_attributes) rounds.reject(&:new_record?).each do |round| attributes = round_attributes[round.id.to_s] if attributes round.attributes = attributes else rounds.delete(round) end end end
Game Helper def fields_for_round(round, &block) prefix = round.new_record? ? 'new' : 'existing' fields_for("game[#{prefix}_round_attributes]", round, &block) end
<% fields_for_round(round) do |f| %> <% @class = cycle("", "alt", :name => "colors") -%> <% 3.times do |p| %> <td class="<%= @class -%>"><%= f.select(:action, ["Miss", "Skip", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], :index => nil) %> <%= f.hidden_field :player_id, :value => @game.teams[0].players[p].id %></td> <% end %>
<td width="100%" align="center" class="<%= @class -%>"><%= round_counter + 1 %></td>
<% 3.times do |p| %> <td class="<%= @class -%>"><%= f.select(:action, ["Miss", "Skip", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], :index => nil) %> <%= f.hidden_field :player_id, :value => @game.teams[1].players[p].id %></td> <% end %> <% end %>