简体   繁体   中英

Rails Admin form for has_many association

For instance say, I have an association in one of my model as:

has_many :students

We know rails_admin creates a multi-selection input field in the form where a user can select students.

The multi-selection input lists all the students.

My question is, is there a way to filter those students and only list out some students that satisfy some condition? If there is, how should I proceed? For example, I want to list out only the students who are let's say active.

There are 100 students and 75 of them are active. I want only those 75 to be listed.

In the screenshot below, I want only Demo projects to be displayed on the left.

在此处输入图片说明

Yes, you can use scopes in your parent Model.

Read this for Scopes Read this for rails_admin Scopes

class Teacher < ApplicationRecord
  has_many :students
  scope :active_students, -> { where(active: true) }
end

Then you can use it like:

Teacher.first.active_students

UPDATE:

You have to customize specifically that field of students by using custom field like mentioned here

Yes, you can scope the association like this

  rails_admin do
    edit do
      field :students do
        associated_collection_scope do
          class_room = bindings[:object]

          proc { |scope| scope.where(class_room: class_room) }
        end
      end
    end
  end

You want to add is_active(Boolean) field in your table to maintain your student status active or not. then use scope to filter the students.

Model

class Student< ApplicationRecord
    scope :active_students, -> { where(is_active: true) }
    scope :deactive_students, -> { where(is_active: false) }
end

Calling that scope

@active_students = Student.active_students
@deactive_students = Student.deactive_students

its helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM