呈现仅属于 rails 中特定帐户的用户列表。

Rendering a list of users that only belong to particular account in rails.

我正在使用专家构建具有多个 permission/access 级别的应用程序。我有具有管理员、教师和学生角色的用户。

我赋予管理员创建教室的能力,他们需要以这种形式 select 该教室的老师。 selector 应该只列出该学校以外的教师(用户)。问题是它列出了数据库中所有具有教师角色的用户。

如何只显示属于该学校的教师?

这是表格

   <% if user.school.teachers %>
        <div class="form-group">
          <%= f.label :teacher_id %>
          <%= f.text_field :teacher_id, class: "form-control" %>
        </div>
    <% end %>

这是我的学校模型

class School < ActiveRecord::Base
    has_many :users
    has_many :classrooms

validates_uniqueness_of :code

    def students
      self.users.students
    end

    def teachers
       self.users.teachers
    end

    def admins
       self.users.admins
    end
end

课堂模型

class Classroom < ActiveRecord::Base

belongs_to :school
belongs_to :teacher, :class_name => "User"
has_and_belongs_to_many :users

has_many :pins
has_many :reflections


validates_presence_of :school
validates_presence_of :teacher
validates :code, :uniqueness => { :scope => :school_id }


end 

以下是我对您的问题的理解:

在您的学校模型中,self.users 列出了属于某个学校的所有用户。所以我们需要,为了只得到教师,通过说 "I only want users with the teacher status".

来过滤这个列表

因此,当您编写 self.user.teachers 时,它会在您的用户模型中查找 teachers 方法。而且我猜这个方法并没有达到你想要的效果。

我认为这可能是您遇到错误的地方,您可以通过添加用户模型来编辑 post 以便确定吗?

要扩展 Calibou 的答案,请在您的教室控制器中调用您的教师方法以将列表传递给视图。

def new
  @school = School.find(params[:id])
  @teachers = @school.teachers
end

那么对于你的表单:

<% if @teachers.present? %>
  <div class="form-group">
    <%= f.collection_select(:teacher_id, @teachers, :id, :name) %>
  </div>
<% end %>

查看文档中的 collection_select here