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

Rails 4 : Updating attribute with an array driven by radio buttons

这个问题非常类似于:Multiple radio button groups who send data in an array 但我似乎无法跳转到我的用例。

我正在为一个总是有 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 而不是您的 "roles".

的值