首页 > 解决方案 > Has_many :通过使用 3 个模型的关联

问题描述

我有 3 个模型teacherstudentsubject

我想获得由我要提供的特定和参数Students处理的列表。teachersubjectsubjectsubject_name

我怎样才能使用has_many :through关联来做到这一点?我试过这个

老师.rb

class Teacher < ApplicationRecord
  has_many :subject_type
  has_many :students, :through=>:subject_type
end

学生.rb

class Student < ApplicationRecord
  has_many :subject_type
  has_many :teachers, :through=>:subject_type
end

主题.rb

class Subject < ApplicationRecord
 has_many :subject_type
end

一个额外的模型是 subject_type.rb

class SubjectType < ApplicationRecord
  belongs_to :teacher
  belongs_to :student
end

方法的控制器是 analytics_controller.rb

class AnalyticsController < ApplicationController
  def get_students_by_teacher_through_subject
    s1 = Subject.find_by(subject_name:params[:subject_name])
    get_teacher = s1.teachers
    render json: get_teacher
  end
end

提前致谢

标签: ruby-on-rails-5

解决方案


推荐阅读