Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array into hidden_field ROR

I'm trying to pass an array into a hidden_field.

The following User has 3 roles [2,4,5]

>> u = User.find_by_login("lesa")
=> #<User id: 5, login: "lesa", email: "[email protected]", crypted_password: "0f2776e68f1054a2678ad69a3b28e35ad9f42078", salt: "f02ef9e00d16f1b9f82dfcc488fdf96bf5aab4a8", created_at: "2009-12-29 15:15:51", updated_at: "2010-01-06 06:27:16", remember_token: nil, remember_token_expires_at: nil>
>> u.roles.map(&:id)
=> [2, 4, 5]

Users/edit.html.erb

<% form_for @user do |f| -%>
<%= f.hidden_field :role_ids, :value => @user.roles.map(&:id) %>

When I submit my edit form, I receive an error: ActiveRecord::RecordNotFound in UsersController#update "Couldn't find Role with ID=245"

How can I pass an array into the hidden_field?

like image 675
JZ. Avatar asked Jan 06 '10 18:01

JZ.


4 Answers

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.

like image 121
Grant Hutchins Avatar answered Nov 19 '22 23:11

Grant Hutchins


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 %> 
like image 34
Matteo Melani Avatar answered Nov 19 '22 23:11

Matteo Melani


Try:

 <% @user.roles.each_with_index do |role| %>
    <%= f.hidden_field "role_ids[]", :value => role.id %>
 <% end %>
like image 3
jamuraa Avatar answered Nov 19 '22 22:11

jamuraa


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.

like image 3
mendokusai Avatar answered Nov 19 '22 23:11

mendokusai