avi*_*ian 6 ruby-on-rails belongs-to ruby-on-rails-3
我有三个模型游戏 > 团队 > 玩家,我希望能够提交以下内容以添加游戏以及这些团队中的多个团队和玩家。
{"game"=>{"name"=>"championship", "teams_attributes"=>[
{"result"=>"won", "players_attributes"=>{"name"=>"Bob"}},
{"result"=>"lost", "players_attributes"=>{"name"=>"Tad"}}]}}
Run Code Online (Sandbox Code Playgroud)
这是我的模型:
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
Run Code Online (Sandbox Code Playgroud)
当我添加一个游戏时,我可以让它添加两个团队,但我不能让它添加一个游戏,在每个团队中添加两个团队和球员。我的设置有问题吗?尝试添加时,我不断收到“无法将字符串转换为整数”错误。这与我刚使用 Games > Teams 时遇到的错误相同,但在添加 inverse_of 内容时已修复。
谢谢!
弄清楚了...是我的哈希设置的问题。正在使用:
{
"game" => {
"name" => "championship",
"teams_attributes" => [
{"result" => "won", "players_attributes" => {"name" => "Bob"}},
{"result" => "lost", "players_attributes" => {"name" => "Tad"}}
]
}
}
Run Code Online (Sandbox Code Playgroud)
但应该是(玩家属性值周围的括号]:
{
"game" => {
"name" => "championship",
"teams_attributes" => [
{"result" => "won", "players_attributes" => [{"name" => "Bob"}]},
{"result" => "lost", "players_attributes" => [{"name" => "Tad"}]}
]
}
}
Run Code Online (Sandbox Code Playgroud)