【问题标题】:Rails - Linking existing models in HABTMRails - 在 HABTM 中链接现有模型
【发布时间】:2014-09-30 20:27:03
【问题描述】:

我有两个这样的模型

class Student
   has_and_belongs_to_many :classrooms
end

class Classrooms
   has_and_belongs_to_many :students
end

我想带一个学生并将他链接到数据库中存在的课程, 每当我尝试这样做时

classroom = Classroom.find(id)
student = Student.find(id)
Student.classrooms.create(classroom: classroom)

我收到这样的错误:

ActiveRecord::UnknownAttributeError: unknown attribute: classroom

【问题讨论】:

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


    【解决方案1】:
    classroom = Classroom.find(classroom_id)
    student = Student.find(student_id)
    
    classroom.students << student
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多