开发者

Creating a has_many association in a hidden-field

开发者 https://www.devze.com 2022-12-21 16:09 出处:网络
Say User has_many Things.In a User form, I\'d like a hidden_field that 开发者_如何学Golets me create a relationship between this new User and a pre-existing Thing, say of id 8.What\'s wrong with the f

Say User has_many Things. In a User form, I'd like a hidden_field that 开发者_如何学Golets 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 %>


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消