2

Say User has_many Things. In a User form, I'd like a hidden_field that lets me create a relationship between this new User and a pre-existing Thing, say of id 8. What's wrong with the following code snippet? I think I'm just forgetting some syntax here.

<% f.hidden_field 'things[]', :value => 8 %>
Newy
  • 38,977
  • 9
  • 43
  • 59

2 Answers2

10

For the posterity... If you have multiple values for 'things' that needs to be sent to the server in array, here is how to make it work:

<% user.things.each do |thing| %>
    <% f.hidden_field 'thing_ids][', :value => thing.id %>
<% end %>

Notice the reverse brackets with things_ids][. If brackets are not reversed server gets "thing_ids"=>[nil, nil], supposing user had 2 things. With reversed brackets you will get correct thing ids in param thing_ids array.

Zeeshan
  • 3,462
  • 2
  • 25
  • 28
6
<% f.hidden_field 'thing_id[]', :value => 8 %>
ghoppe
  • 21,452
  • 3
  • 30
  • 21