在Active Admin Rails中创建新项目时过滤下拉列表

问题描述 投票:1回答:1

我有一个Rails 5应用程序,它使用Devise通过标准的User模型进行注册和会话。我也有Rolify与两种角色(学生,教师)相结合。

class User < ApplicationRecord
  rolify
  mount_uploader :avatar, AvatarUploader

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates_integrity_of  :avatar
  validates_processing_of :avatar


  include PgSearch
  pg_search_scope :search_by_full_name, against: [:full_name],using: {
    tsearch: {
      prefix: true,
      highlight: {
        start_sel: '<b>',
        stop_sel: '</b>',
      }
    }
   }



  private
    def avatar_size_validation
      errors[:avatar] << "should be less than 500KB" if avatar.size > 0.5.megabytes
    end
end

我想展示一些特色老师,所以我有一个名为featured_teachers的表。迁移如下。

class CreateFeaturedTeachers < ActiveRecord::Migration[5.2]
  def change
    create_table :featured_teachers, id: :uuid do |t|
      t.references :user, foreign_key: true,type: :uuid

      t.timestamps
    end
  end
end

相关的FeaturedTeacher模型如下所示

class FeaturedTeacher < ApplicationRecord
  belongs_to :user
end

我想使用Active Admin来管理特色教师,因此我创建了以下Active Admin资源。

ActiveAdmin.register FeaturedTeacher do

permit_params :user_id
actions :index,:new, :destroy
index do
    selectable_column
    column :user
    column :created_at
    actions name: "Actions"
end
end

但正在发生的是,当我想添加一个新的特色教师时,我在下拉列表中获得了数据库中用户的完整列表。

我想要做的是只显示角色类型为“老师”的用户,以及在Active Admin用户界面中将新用户添加到精选教师列表时尚未添加到精选教师表的用户。

请有人帮我这个吗?我对Ruby和Rails有点新意,并希望了解如何完成这项工作。我很可能也需要在其他Active Admin界面中使用它。

谢谢。

ruby-on-rails devise activeadmin rolify
1个回答
1
投票

您需要为特色教师创建表单,请在featured_teachers.rb活动管理文件中添加以下代码

form do |f|
    f.inputs 'Featured Teacher' do
      # in the select box only load those users which are teacher and not in featured teacher list you need to add query for it
      f.input :user, as: :select, collection: User.where(role: 'teacher').map { |u| [u.name, u.id] }, include_blank: true, allow_blank: false, input_html: { class: 'select2' }
     # please also add other fields of featured teacher model

您可以在活动管理文档here中查看所有可用选项

© www.soinside.com 2019 - 2024. All rights reserved.