微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – seed.rb中的关联

我的应用程序中有以下模型

class Building < ApplicationRecord

  has_many :rooms,dependent: :destroy
  ...

class Room < ApplicationRecord

  belongs_to :building
  has_many :lessons,dependent: :destroy
  ...

class Lesson < ApplicationRecord

  belongs_to :room
  belongs_to :teacher
  belongs_to :course
  ...

使用以下代码,Bulding及其房间之间的一切正常:

if Building.find_by_code("PAR").nil?
   building = Building.create!({title: "Areál Parukářka",code: "PAR"})

   par_rooms.each do |room|
      building.rooms << Room.create({title: room[0],code: room[1]})
   end 
end

现在我想为每个房间添加课程.使用以下代码,不会引发错误,当我添加一些“puts”时,它表示已经创建了课程,但它们在控制器/视图中不可用.这是我使用的种子:

if Building.find_by_code("PAR").nil?
  building = Building.create!({title: "Areál Parukářka",code: "PAR"})

  par_rooms.each do |room|
    new_room = Room.create({title: room[0],code: room[1]})
    building.rooms << new_room
    lesson = Lesson.create({start_at: DateTime.new(2018,11,20,8),end_at: DateTime.new(2018,9,30),durration: 45,room_id: new_room.id,teacher_id: nil,course_id: nil})
    new_room.lessons << lesson
  end

房间和课程表具有以下架构:

create_table "rooms",force: :cascade do |t|
    t.string "title"
    t.string "code"
    t.datetime "created_at",null: false
    t.datetime "updated_at",null: false
    t.integer "building_id"
    t.index ["building_id"],name: "index_rooms_on_building_id"
  end


create_table "lessons",force: :cascade do |t|
    t.datetime "start_at"
    t.datetime "end_at"
    t.integer "durration"
    t.datetime "created_at",null: false
    t.integer "room_id"
    t.integer "teacher_id"
    t.integer "course_id"
    t.index ["course_id"],name: "index_lessons_on_course_id"
    t.index ["room_id"],name: "index_lessons_on_room_id"
    t.index ["teacher_id"],name: "index_lessons_on_teacher_id"
  end

解决方法

lesson = Lesson.create({
  start_at: DateTime.new(2018,# is problematic with your model
  course_id: nil})     # is problematic with your model

你的模型表明需要所有的关系.
你应该,如果有空关系,请标记

belongs_to :teacher,optional: true

作为可选.

并不是说这解决了你的问题,但它应该是正确的方向.要获得更多想法,您应该为教师,课程,房间和建筑提供图式.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐