我有3个模型:teacher
,student
和subject
。
我想获取由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
预先感谢