Creating a has_many association on a hidden field

Say the user has_many Things. In the user form, I would like a hidden field to allow me to create a relationship between this new user and a pre-existing Thing, for example ID 8. What happened to the following piece of code? I think I just forgot about the syntax here.

<% f.hidden_field 'things[]', :value => 8 %>

      

+2


source to share


2 answers


<% f.hidden_field 'thing_id[]', :value => 8 %>

      



+6


source


For posterity ... If you have multiple values ​​for "things" to be sent to the server in an array, here's how to do it:

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

      



Notice the parentheses with items_ids] [. If the brackets are not inverted, the server gets "thing_ids"=>[nil, nil]

if the user had 2 things. With the feedback brackets, you get the correct object ids in the param thing_ids array.

+9


source







All Articles