2013-08-19 23 views
4

我有三個模型遊戲>團隊>玩家,我希望能夠提交以下內容以添加一個遊戲以及這些團隊中的多個團隊和玩家。無法獲得accep_nested_attributes_for深入兩個級別的工作?

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

這裏是我的模型:

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 

我可以得到它添加兩個隊,當我加一個遊戲,但我不能把它添加一個遊戲,每增加兩個球隊和球員球隊。我的設置有問題嗎?嘗試添加時,我總是收到「無法將字符串轉換爲整數」錯誤。這與我剛獲得Games> Teams時得到的錯誤是一樣的,但是當我添加inverse_of時,這個錯誤得到修復。

謝謝!

+0

你能提供你的控制器代碼和視圖代碼,以及也可能是具體的錯誤,包括行號和全錯誤信息? – Vapire

+0

哦,我看到了太晚了,但在Rails中沒有'belongs_to through'關聯! – Vapire

+0

嗨!我的控制器是超級基本的,只是調用Game.create(...) – Hawk

回答

1

想通了......是我的散列設置問題。 用那句話:

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

但應該是(約players_attributes括號]:

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