Has_many:通过使用3个模型的关联

时间:2019-05-22 07:40:29

标签: ruby-on-rails-5

我有3个模型:teacherstudentsubject

我想获取由Students处理的teacher的列表,该列表在特定的subject中,并在subject的参数中提供subject_name

如何使用has_many :through关联进行操作? 我尝试过了

teacher.rb

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

student.rb

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

subject.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

预先感谢

0 个答案:

没有答案