1

我需要使用数组中的对象作为collection_select使用帮助器的表单中的对象参数,form_tag但我的 params 哈希格式不正确。

例子:

<%= form_tag(picks_path, method: :post) do %>
  <% @awards.each do |award| %>

    <%= hidden_field_tag "picks[][user_id]", 1 %>
    <%= hidden_field_tag "picks[][game_id]", 1 %>
    <%= hidden_field_tag "picks[][award_id]", award.id %>

    <%= label_tag "picks[][:first_pick]", "First Pick" %>
    <%= collection_select("picks[][:first_pick]",
         :first_pick, award.nominations, :id, :nominee) %>

  <% end %>

<%= submit_tag 'Submit' %>
<% end %>

结果在此参数哈希中带有额外的嵌套...

"picks"=>[{"user_id"=>"1", "game_id"=>"1", "award_id"=>"1", ":first_pick"=>{"first_pick"=>"1"}}, {"user_id"=>"1", "game_id"=>"1", "award_id"=>"2", ":first_pick"=>{"first_pick"=>"3"}}]

当我真正想要的是这个...

"picks"=>[{"user_id"=>"1", "game_id"=>"1", "award_id"=>"1", "first_pick"=>"1"}, {"user_id"=>"1", "game_id"=>"1", "award_id"=>"2", "first_pick"=>"3"}]

我试过用这个...

<%= collection_select("picks[]", :first_pick, award.nominations, :id, :nominee) %>

但我得到了这个例外......

object[] 命名但 object param 和 @object var 不存在或不响应 to_param: nil

我是否在这里遗漏了一些特殊语法,或者这不是通过一个提交按钮从表单中实现多个条目的传统方式?

4

1 回答 1

0

试试each.inject,像这样:

<% @awards.each.inject([]) do |collection_select, award| %> collection_select << { first_pick: award[:first_pick], nominations: award[:nominations], id: award[:id], nominee: award[:nominee]}

If your award main object don't hold some values, u can hard coded it in each hash value i.e: id: 1, nominee: 'anything'

希望能帮助到你。

于 2017-02-25T00:59:30.637 回答