使用嵌套属性实现多选下拉列表

时间:2017-04-04 11:43:31

标签: ruby-on-rails ruby mongodb ruby-on-rails-5 nested-attributes

我正在尝试实施多选下拉菜单,但我遇到了一些问题。

1)在我的情况下,多次下拉即将到来我无法弄清楚

2)如果我编辑任何用户,他所拥有的所有标签都应该在多选下拉列表中被选中。所有标签都应该出现,以便如果他想更新他的标签或更改他的标签,他就可以做到。

User.rb

...
compile 'com.google.dagger:dagger:2.9'
apt 'com.google.dagger:dagger-compiler:2.9'
...

Tag.rb

 class User
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      include Mongoid::Document
      include Mongoid::Timestamps

     devise :database_authenticatable, :registerable,
            :recoverable, :rememberable, :trackable, :validatable, :confirmable#, :omniauthable, :omniauth_providers => [:facebook]


      has_many :tags,dependent: :destroy
      accepts_nested_attributes_for :tags,allow_destroy: true

    end

users_controller.rb

 class Tag
      include Mongoid::Document
      include Mongoid::Timestamps

       belongs_to :user

       field :name, :type => String

       field :created_at, :type => DateTime
       field :updated_at, :type => DateTime


    end

用户/ edit.html.erb

class UsersController < ApplicationController
    before_action :authenticate_user!


    def index
        @users = User.all - [User.find_by(status: true)]
    end


    def show
        @user = User.find(params[:id])   
    end

    def edit
        @user = User.find(params[:id])
    end


    def update
        @user = User.find(params[:id])
        if @user.update_attributes(user_params)
            redirect_to users_path      
        else
          render 'edit'
        end
    end

    private

        def user_params
          params.require(:user).permit(:first_name, tags_attributes: [:id, :name, :_destroy] )
        end


end

enter image description here

1 个答案:

答案 0 :(得分:0)

根据APIdoc

  

将重复给嵌套fields_for调用的块   集合中的每个实例