开发者

A Many-Many Association Hidden_Field edit problem. 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: "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"

Next I attempted to edit my users/edit.html.erb to:

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

Yielding what I believe is a string: "role_ids"=>"2, 4" (Required Output: "role_ids"=>["2", "4"])

When I attempted using a loop:

<% for role in Role.find(:all) %>
    <%= f.hidden_field :role_ids, :value => @user.roles.map(&:id).join(",").to_a开发者_如何转开发 %>
    <% end %>

Yet another string resulted:

Parameters: {"commit"=>"Update", "action"=>"update", "_method"=>"put", "authenticity_token"=>"84Fvxxo3ao8Fl+aytOFInrLatUpslfAJggleEyy4wyI=", "id"=>"5", "controller"=>"users", "user"=>{"password_confirmation"=>"[FILTERED]", "role_ids"=>"2, 4, 5", "password"=>"[FILTERED]", "login"=>"lesa", "email"=>"lesa@gmail.com"}}

Any suggestions? This has been a perplexing problem.


If you want to submit an array of values I believe you can do something like this:

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

Rails should then merge the value of each hidden field with the same name 'role_ids[]' into an array giving you something like this:

Parameters: {"commit"=>"Update" ... "role_ids"=>["2", "4", "5"], ... }}


The accepted answer doesn't work for me. It works if you're using hidden_field_tag but not with f.hidden_field. I need to resort to

<%= f.hidden_field 'role_ids][', value: role.id %>

Note the reversed bracket.


if you pass just the u.roles.map(&:id)[0] what happens? is the value = 2? Maybe the value don't accept multivalue or maybe you should pass
<%= f.hidden_field :role_ids, :value=>“#{u.roles.map(&:id).join(',')}">


You could do the work in the controller edit action (air code):

@role_ids = @user.roles.map(&:id).join(";")

In the form:

<%= f.hidden_field, 'role_ids', :value => @role_ids %>

Then in the update action:

roles = params[:user][:role_ids].split(";")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜