Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get accepts_nested_attributes_for to work for two levels deep?

I have three models Game > Team > Players and I want to be able to submit the following to add a game along with multiple teams and players on those teams.

{"game"=>{"name"=>"championship", "teams_attributes"=>[
    {"result"=>"won", "players_attributes"=>{"name"=>"Bob"}}, 
    {"result"=>"lost", "players_attributes"=>{"name"=>"Tad"}}]}}

Here are my models:

class Game < ActiveRecord::Base
   attr_accessible  :name, :teams_attributes, :players_attributes

   # Associations
   has_many :teams, :inverse_of => :game
   has_many :players, :through => :teams

   accepts_nested_attributes_for :teams
   accepts_nested_attributes_for :players
end

class Team < ActiveRecord::Base
     attr_accessible :game_id, :result, :players_attributes

     # Associations
     belongs_to :game, :inverse_of => :teams
     has_many :players, :inverse_of => :team

     accepts_nested_attributes_for :players
end

class Player < ActiveRecord::Base
  attr_accessible :team_id, :name

  # Associations
  belongs_to :team, :inverse_of => :players
  # belongs_to :game, :through => :team (causes error, doesn't fix)

end

I can get it to add two teams when I add a game, but I cannot get it to add a game, add two teams and players on each team. Am I doing something wrong with my setup? I keep getting the "can't convert String into Integer" error when trying to add. This is the same error I was getting when I just had Games > Teams, but was fixed when I added the inverse_of stuff.

Thanks!

like image 789
avian Avatar asked Aug 19 '13 09:08

avian


1 Answers

Figured it out... was an issue with my hash setup. Was using:

{"game"=>{"name"=>"championship", "teams_attributes"=>[
{"result"=>"won", "players_attributes"=>{"name"=>"Bob"}}, 
{"result"=>"lost", "players_attributes"=>{"name"=>"Tad"}}]}}

But should be (brackets around players_attributes]:

{"game"=>{"name"=>"championship", "teams_attributes"=>[
{"result"=>"won", "players_attributes"=>[{"name"=>"Bob"}]}, 
{"result"=>"lost", "players_attributes"=>[{"name"=>"Tad"}]}]}}
like image 129
avian Avatar answered Nov 06 '22 21:11

avian