Rails 4:使用由单选按钮驱动的数组更新属性



这个问题非常类似于:多个单选按钮组在一个数组中发送数据,但我似乎无法跳转到我的用例。

我正在为一个总是有8个角色(:strategy_cards)的游戏建模,我想将其作为数组传递。这些角色中的每一个都可以是几个价值观中的一个。

@games.select_strategy_cards传回我的散列:

{"Initiative" => 1, "Diplomacy" => 2, "Political" => 3, "Logistics" => 4, "Trade" => 5, "Warfare" => 6, "Technology" => 7,"Imperial" => 8, "Leadership" => 1,"Diplomacy II" => 2,"Assembly" => 3,"Production" => 4,"Trade II" => 5,"Warfare II" => 6,"Technology II" => 7,"Bureaucracy" => 8,"Imperial II" =>8, "Trade III" => 5,"Political II" => 3,"Assembly II" => 3}

这是我迄今为止的代码:

<% i=[*1..8].each do |v| %>
<div>
<h2><%= v %></h2>
<% @game.select_strategy_cards.each do |key, value| %>
<% if value == v %>
<%= f.label key %>
<%= radio_button_tag "game[strategy_cards][#{value}]", key  %>
<% end %>
<% end %>
</div>
<% end %>

它生成标记为1-8的div,并根据需要创建单选按钮。我认为我的问题是"game[strategy_cards][#{value}]">

但我一辈子都想不出来。

更新

已更改

按照Ryan的建议。散列看起来创建得很好(尽管数组会更好):

Started PATCH "/games/98/game_steps/strategy_cards" for ::1 at 2015-04-17 19:53:26 -0700
Processing by GameStepsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4eQPqXt9tMo/ZJ4mvgT8JJ4QmLVSqqZoayIv1Zt/2c7yFmikOIgGJH2Vc0vdt3UOBlF7H0jH8mDRaTs3VFTgDg==", "game"=>{"strategy_cards"=>{"1"=>"Leadership", "2"=>"Diplomacy II", "3"=>"Assembly II", "4"=>"Production", "5"=>"Trade III", "6"=>"Warfare II", "7"=>"Technology II", "8"=>"Imperial II"}}, "commit"=>"Update Game", "game_id"=>"98", "id"=>"strategy_cards"}
[1m[36mGame Load (0.1ms)[0m  [1mSELECT  "games".* FROM "games" WHERE "games"."id" = ? LIMIT 1[0m  [["id", 98]]
Unpermitted parameters: 1, 2, 3, 4, 5, 6, 7, 8
[1m[35m (0.1ms)[0m  begin transaction
[1m[36mSQL (0.2ms)[0m  [1mUPDATE "games" SET "strategy_cards" = ?, "updated_at" = ? WHERE "games"."id" = ?[0m  [["strategy_cards", "{}"], ["updated_at", "2015-04-18 02:53:26.708415"], ["id", 98]]
[1m[35m (1.2ms)[0m  commit transaction
[1m[36m (0.1ms)[0m  [1mbegin transaction[0m
[1m[35m (0.0ms)[0m  commit transaction
Redirected to http://localhost:3000/games/98/game_steps/wicked_finish
Completed 302 Found in 5ms (ActiveRecord: 1.6ms)

但它并没有更新:strategy_cards。这是我的许可证:

def game_params
params.require(:game).permit(:shattered_empire, :shards_of_the_throne, :number_of_players, {:rules => []}, {:strategy_cards => []}, :players, {:races => []})
end

更新2

因此,问题似乎是:

未经许可的参数:1、2、3、4、5、6、7、8

将我的许可证更改为许可证!确实允许散列通过,但这似乎不是最佳的。

更新3

有点恶心,但

def game_params
params.require(:game).permit(:shattered_empire, :shards_of_the_throne, :number_of_players, {:rules => []}, {:strategy_cards => [:"1",:"2",:"3",:"4",:"5",:"6",:"7",:"8"]},:players, {:races => []})
end

似乎应该更改

<%= radio_button_tag "game[strategy_cards][#{value}]", key  %>

至:

<%= radio_button_tag "game[strategy_cards][#{v}]", key  %>

这样,它们被列为1..8,而不是您的"角色"的值。

最新更新