传递一个数组hidden_field ROR [英] Passing an array into hidden_field ROR
问题描述
我想一个数组传递到一个hidden_field。
I'm trying to pass an array into a hidden_field.
以下的用户有3个角色[2,4,5]
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]
用户/ edit.html.erb
Users/edit.html.erb
<% form_for @user do |f| -%>
<%= f.hidden_field :role_ids, :value => @user.roles.map(&:id) %>
当我提出我的编辑形式,我收到一个错误:的ActiveRecord :: RecordNotFound在UsersController#更新的<strong>无法找到ID角色= 245
When I submit my edit form, I receive an error: ActiveRecord::RecordNotFound in UsersController#update "Couldn't find Role with ID=245"
如何传递一个数组到hidden_field?
How can I pass an array into the hidden_field?
推荐答案
我会用这个技术。
<% @user.roles.each do |role| %>
<%= f.hidden_field :role_ids, :multiple => true, :value => role.id %>
<% end %>
:多个
添加两个 []
来的name属性的结束和多个=多个
来输入元素,这是理想的。 Rails使用这个内部时,它会为阵列输入,如 fields_for
。
: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.
这篇关于传递一个数组hidden_field ROR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!