Passing an array into hidden_field ROR

拈花ヽ惹草 提交于 2019-11-29 20:16:50

I would use this technique.

<% @user.roles.each do |role| %>
    <%= f.hidden_field :role_ids, :multiple => true, :value => role.id %>
<% end %>

:multiple adds both the [] to the end of the name attribute and multiple="multiple" to the input element, which is ideal. Rails uses this internally when it generates inputs for arrays, such as in fields_for.

Unfortunately it is not well-documented. I'm going to look into fixing this.

The only thing that works for me (Rails 3.1) is using hidden_field_tag:

<% @users.roles.each do |role| %>
    <%= hidden_field_tag "user_role_ids[]", role.id %>
<% end %> 

I think it still will be helpful for people like me, who googled this tread asking the same question. I came up with the next little hack:

<%= f.hidden_field "role_ids][", { :id => "role_ids", :value => [] } %>

(pay attention to the reversed brackets in 'object_name' argument for hidden field).

Try:

 <% @user.roles.each_with_index do |role| %>
    <%= f.hidden_field "role_ids[]", :value => role.id %>
 <% end %>

using Rails 4.2.6

I was able to use

<% @user.roles.each do |role|
  <%= f.hidden_field :role_ids, :id => role.id, :value => role.id, :multiple => true %>
<% end %>

which rendered:

<input id="12345" value="12345" multiple="multiple" type="hidden" name="role_form[role_ids][]">

trying to use hidden_field_tag or the 'role_ids[]' the param details were not being included in my form_params.

This didn't work:

<% @user.roles.each do |role|
  <%= hidden_field_tag 'role_ids[]', role %>
<% end %>

because it renders:

<input type="hidden" name="role_ids[]" id="role_ids_" value="12345">

and is seen by the controller outside of the form params.

try with:

<%= f.hidden_field :role_ids, :value => @user.roles.map(&:id).join(", ") %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!