Rails:使用数组中的对象作为collection_select的对象参数

时间:2017-02-24 19:33:06

标签: ruby-on-rails forms collection-select

我需要在使用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 %>

带有额外嵌套的这个params哈希结果...

"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 var不存在或不存在   回复to_param:nil

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

1 个答案:

答案 0 :(得分: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'

希望它有所帮助。