ruby-on-rails-5 - Has_many :通过使用 3 个模型的关联
问题描述
我有 3 个模型teacher
:student
和subject
。
我想获得由我要提供的特定和参数Students
处理的列表。teacher
subject
subject
subject_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
提前致谢
解决方案
推荐阅读
- c# - ef核心一对多关系抛出异常无法添加或更新子行
- python - 从 mypy 中删除 Python 类中动态设置的属性的错误
- php - 带有目标c的Xcode将json数据发布到php api
- node.js - 使用 Node.JS 进行 API 设计
- javascript - 如何将数据库嵌入到我的 vuejs 应用程序中?
- python - 免费的 Mysql 或 Python 缓存
- node.js - 续集错误:找不到未定义的属性“startYear”
- javascript - 使用 jQuery 进行文本镜像
- email - 在过滤电子邮件时配置 procmail 以匹配外部电子邮件地址列表
- android - Android Studio 模拟器错误