Ассоциации в seed.rb - PullRequest
       9

Ассоциации в seed.rb

0 голосов
/ 20 ноября 2018

В моем приложении есть следующие модели

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
  ...

Все отлично работало между Булдингом и его комнатами с этим кодом:

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 

Теперь я хочу добавить уроки в каждую комнату.В следующем коде ошибка не возникает, и когда я добавляю несколько «put», он говорит, что уроки созданы, но они недоступны внутри контроллера / представления.Вот семя, которое я использую:

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

Таблицы комнат и уроков имеют следующую схему:

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 голосов
/ 21 ноября 2018
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

как необязательное.

не для того, чтобы это решило вашу проблему, но это должно быть правильное направление.для большего количества идей вы должны предоставить схемы для учителя, курса, комнаты и здания.

0 голосов
/ 21 ноября 2018

Попробуйте new_room = building.rooms.create({title: room[0], code: room[1]}) и удалите строку building.rooms << new_room

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...