我正在使用Embedded Ruby
和Rails 4
来创建和编辑用户的表单。创建时必须为每个用户分配一个角色。最初,表单为此使用复选框并且工作正常。但是,在切换到单选按钮时,我收到错误。
这是形式:
<%= simple_form_for(@user, html: {class: 'form-horizontal'}) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name, autofocus: true %>
<%= f.input :email %>
<%= f.input :phone_number %>
<%= f.input :institution_pid, collection: institutions_for_select, as: :select, label: "Institution" %>
<%= f.association :roles, collection: roles_for_select, as: :radio_buttons %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
</div>
<br>
<div class="form-actions">
<%= button_tag(type: 'submit', class: "btn doc-action-btn btn-success") do %>
<i class="glyphicon glyphicon-check"></i> Submit
<% end %>
<%= link_to @user, {class: "btn doc-action-btn btn-cancel"} do %>
<i class="glyphicon glyphicon-remove"></i> Cancel
<% end %>
</div>
我特别问的是f.association
位。以前,当我使用
as: :check_boxes
它完全按照预期工作。现在我收到此错误消息:
NoMethodError in UsersController#update
undefined method `reject' for "77":String
我应该注意,"77"是其中一个单选按钮选项的值。
引发错误的方法是这样的:
def build_role_ids
[].tap do |role_ids|
roles = Role.find(params[:user][:role_ids].reject &:blank?)
roles.each do |role|
authorize!(:add_user, role)
role_ids << role.id
end
end
end
使用单选按钮时的 HTML 如下所示:
<label class="radio">
<input class="radio_buttons optional" id="user_role_ids_77" name="user[role_ids]" type="radio" value="77">
"Institutional Admin"
</label>
使用复选框时:
<label class="checkbox">
<input class="check_boxes optional" id="user_role_ids_77" name="user[role_ids][]" type="checkbox" value="77">
"Institutional Admin"
</label>
如果我遗漏了什么,或者您需要更多信息,请告诉我。谢谢!
使用复选框,用户可以选择多个值,以便您获得params[:user][:role_ids]
中返回的role_ids Array
。 reject
方法是为数组实现的。因此,它在这种情况下有效。
使用单选按钮,一次只会选择一个值,因此您将获得params[:user][:role_ids]
中role_ids
的String
值。 reject
方法未实现字符串。因此,错误。
而不是
params[:user][:role_ids].reject &:blank?
您可以检查role_ids
是否为空,因为它是一个字符串对象。
params[:user][:role_ids].empty?
并更新build_role_ids
方法,请记住role_ids
是字符串对象而不是数组。
此错误似乎表明params[:user][:role_ids]
不是Array
而是单个String
值。这是有意义的,因为您正在从复选框(一次可以选择多个值 = 数组)更改为单选按钮(一次只能选择一个值 = 字符串)。
如果确实要从复选框更改为单选按钮,则需要更新build_role_ids
方法逻辑,使其需要单个值而不是值数组。