seed.rb中的关联

时间:2018-11-20 20:03:59

标签: ruby-on-rails ruby-on-rails-5

我的应用中有以下型号

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, 11, 20, 9, 30), durration: 45, room_id: new_room.id, teacher_id: nil, course_id: nil})
    new_room.lessons << lesson
  end

rooms和Lessons表具有以下架构:

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.datetime "updated_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

2 个答案:

答案 0 :(得分:1)

lesson = Lesson.create({
  start_at: DateTime.new(2018, 11, 20, 8), 
  end_at: DateTime.new(2018, 11, 20, 9, 30), 
  durration: 45, room_id: new_room.id, 
  teacher_id: nil,     # is problematic with your model
  course_id: nil})     # is problematic with your model

您的模型表明所有关系都是必需的。 如果给出的是空关系,则应标记

belongs_to :teacher, optional: true

(可选)。

这不能解决您的问题,但这应该是正确的方向。 要获得更多创意,您应该提供教师,课程,教室和建筑物的架构。

答案 1 :(得分:0)

尝试new_room = building.rooms.create({title: room[0], code: room[1]}),然后删除行building.rooms << new_room