Passing an array into hidden_field ROR

Viewed 28990

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: "lesa.beaupry@gmail.com", 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?

7 Answers

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 %> 

Try:

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

try with:

<%= f.hidden_field :role_ids, :value => @user.roles.map(&:id).join(", ") %>

edit: note - you'll need to do ids.split(", ") in your controller to convert them from a string into an array

I realize the original question involved a Rails form_for form, but I just encountered this problem while trying adding a hidden field to a form_tag form. The solution is slightly different.

The hidden_field_tag kept converting my ids to a space-separated string, like "1 2 3", not the array of ["1", "2", "3"] that I wanted. According to the docs, this is a known problem with hidden_field_tag. This is the approach that ended up working for my Rails 6 form_tag form:

In the view:

<%= hidden_field_tag :role_ids, my_role_ids_array %>

In the controller:

role_ids = params[:role_ids].split(' ').map(&:to_i)

Could solve this kind of issue with :

      <% params[:filter].each do |filter| %>
        <%= hidden_field_tag 'filter[]', filter %>
      <% end %>
Related