views:

448

answers:

3

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?

A: 

try with:

<%= f.hidden_field :role_ids, :value => @user.roles.map(&:id).join(", ") %>
makevoid
Close but it still doesn't work. Required Output: "role_ids"=>["2", "4"]Actual Output: "role_ids"=>"2, 4"
JZ
A: 

Try:

 <% @user.roles.each_with_index do |role| %>
    <%= f.hidden_field "role_ids[]", :value => role.id %>
 <% end %>
jamuraa
that seems to make a hash - perhaps I'll hack around with it.
JZ
try the new version?
jamuraa
This is close, What ended up working was...<% f.fields_for :users do |builder| %> <%= render 'user_fields', :f => builder %><% end %> THEN <% role = Role.find(:first) %><%= f.hidden_field :role_ids, :value => role.id %>
JZ
A: 

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).

atzkey