【问题标题】:How to add has_many through using the controller for specific cases?如何在特定情况下通过使用控制器添加 has_many?
【发布时间】:2023-03-09 18:41:02
【问题描述】:

我通过名为 Classes 的连接表连接了 Student 和 Teachers 表。 我的目标是通过首先检查老师是否已经存在,然后创建一个新的老师个人资料来将老师添加到学生个人资料中。课程暂时不重要。有人能把我推向正确的方向吗,因为我只是一个初学者,我在指南中找不到解决方案。

class Student < ActiveRecord::Base
  has_many :classes
  has_many :teachers, through: :classes
end

class Class < ActiveRecord::Base
  belongs_to :student
  belongs_to :teacher
end

class Teacher < ActiveRecord::Base
  has_many :classes
  has_many :students, through: :classes
end

感谢你帮助一个菜鸟!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    您说“课程目前不重要”,但您无法在没有课程的情况下连接学生和教师。

    如果你和老师有直接关系,我会这样做;

    1-

    @student.teachers << @teacher unless @student.teachers.include?(@teacher)
    

    2-

    @student.teachers.find_or_create_by(params[:teacher])
    

    3-

    #Rails 3
    @teacher = @student.teachers.find_or_initialize_by_id(params[:teacher_id])
    @teacher.save
    

    4-

    student = @class.build_student
    teacher = @class.build_teacher
    
    student.teachers << teacher
    
    student.save
    teacher.save
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多