Can't get accepts_nested_attributes_for to work at two levels in depth?

I have three models of Game> Team> Players, and I want to be able to send the following to add the game along with several teams and players in these 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 him to add two teams when I add a game, but I can't get her to add a game, add two teams and players to each team. Am I something wrong with my setup? When I try to add, I continue to get the error "cannot convert String to Integer". This is the same error that I received when I had Games> Teams, but it was fixed when I added inverse_of stuff.

Thanks!

+4
source share
1 answer

Figured it out ... there was a problem with my hash setting. Used:

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

But it should be (brackets around players_attributes):

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

Source: https://habr.com/ru/post/1497758/


All Articles