简体   繁体   English

has_many 关联的 Rails 管理表单

[英]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.我们知道rails_admin在表单中创建了一个多选输入字段,用户可以在其中选择学生。

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.有100名学生,其中75名活跃。 I want only those 75 to be listed.我只想列出那 75 个。

In the screenshot below, I want only Demo projects to be displayed on the left.在下面的屏幕截图中,我只想在左侧显示 Demo 项目。

在此处输入图片说明

Yes, you can use scopes in your parent Model. 是的,您可以在父模型中使用范围。

Read this for Scopes Read this for rails_admin Scopes 阅读的作用域阅读本作rails_admin 作用域

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 您必须使用此处所述的自定义字段来专门自定义students的字段

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. 您想在表中添加is_active(Boolean)字段以保持学生状态为活动或不活动。 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! 它有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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