【问题标题】:ERB Radio Button causing string errorERB 单选按钮导致字符串错误
【发布时间】:2014-02-25 16:16:55
【问题描述】:

我正在使用Embedded RubyRails 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>

如果我遗漏了什么或者您需要更多信息,请告诉我。谢谢!

【问题讨论】:

    标签: html ruby-on-rails forms radio-button


    【解决方案1】:

    使用复选框,用户可以选择多个值,因此您会在params[:user][:role_ids] 中返回一个Array 的角色 ID。 reject 方法是为数组实现的。因此,它在这种情况下有效。

    使用单选按钮,一次只能选择一个值,因此您将在params[:user][:role_ids] 中获得role_idsString 值。 reject 方法没有为字符串实现。因此,错误。

    代替

    params[:user][:role_ids].reject &:blank?
    

    你可以检查role_ids是否为空,因为它是一个String对象。

    params[:user][:role_ids].empty?
    

    并更新build_role_ids 方法,记住role_ids 是一个字符串对象,而不是一个数组。

    【讨论】:

    • 我不得不对方法进行更多的编辑,而不仅仅是将那行从数组更改为字符串,但总体思路奏效了。谢谢!
    【解决方案2】:

    此错误似乎表明 params[:user][:role_ids] 不是 Array 而是单个 String 值。这是有道理的,因为您正在从复选框(一次可以选择多个值 = 数组)更改为单选按钮(一次只能选择一个值 = 字符串)。

    如果您真的想从复选框更改为单选按钮,那么您需要更新您的 build_role_ids 方法逻辑以期望单个值而不是值数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多