1

I need to use an object in an array as the object argument for collection_select in a form using a form_tag helper but my params hash isn't formatting correctly.

Example:

<%= 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 %>

Results in this params hash with extra nesting...

"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"}}]

When what I'd really like is this...

"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"}]

I tried using this...

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

But I got this exception...

object[] naming but object param and @object var don't exist or don't respond to to_param: nil

Am I missing some special syntax here or is this not the conventional way of achieving multiple entries from a form with one submit button?

Travis Smith
  • 622
  • 5
  • 22

1 Answers1

0

try each.inject, something like this:

<% @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'

hope it helps.

Bruno
  • 1
  • 2