【问题标题】:How can I Make multi select in simple_fields_for如何在 simple_fields_for 中进行多选
【发布时间】:2014-10-08 12:57:17
【问题描述】:

我写了以下接受角色,如何让它接受多个值

= f.simple_fields_for :content_roles do |role|
  = role.input :role_id, label: "visible to", as: :select, label: "Role", collection: Role.all, required: true

【问题讨论】:

    标签: ruby-on-rails nested-forms polymorphic-associations


    【解决方案1】:

    只需将multiple: true 添加到您的角色字段即可。

    像这样:

    = role.input :role_id, label: "visible to", as: :select, label: "Role", collection: Role.all, required: true, multiple: true
    

    【讨论】:

      【解决方案2】:

      这是在我当前的在线项目中运行的代码。更新了缺少的 ruby​​ 标签....

      【讨论】:

      • edit您提出问题并修复代码降价。
      • 已更新。感谢您指出。但解决方案是正确的。上述解决方案不起作用。这行得通..!
      【解决方案3】:

      以下内容在没有 fields_for 的情况下对我有用,并且仅在我认为必须添加新角色时才应使用

      您可以使用预选值和引导选择选择器来做到这一点:

          = simple_form_for [:backend, @user], html: { autocomplete: 'off' } do |f|
            = f.select :role_ids, options_for_select(Role.all.map{|role| [role.name, role.id]}, @user.role_ids), {},  {:multiple => true, inlcude_blank: false, class: "form-control input-sm selectpicker"}
      

      控制器:

      module Backend
        class UsersController < ApplicationController
          before_action :set_user, only: %i[edit update]
          def index
            @users = User.all
          end
      
          def edit
            @user.roles.build unless @user.roles.any?
          end
      
          def update
            if @user.update user_params
              redirect_to backend_users_path(@user), notice: 'Rollen erfolgreich aktualisiert'
            else
              render :edit
            end
          end
      
          private
      
          def set_user
            @user = User.find(params[:id])
          end
      
          def user_params
            params.require(:user).permit(:id, role_ids: [])
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-12
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多