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

标签 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 

现在我想为每个房间添加类(class)。使用以下代码,不会引发任何错误,当我添加一些“放置”时,它表示类(class)已创建,但它们在 Controller / View 中不可用。这是我使用的种子:
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

房间和类(class)表具有以下架构:
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

最佳答案

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

作为可选。

并不是说这解决了您的问题,而是应该是正确的方向。
对于更多想法,您应该提供教师、类(class)、房间和建筑的模式。

关于ruby-on-rails - seed.rb 中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400717/

相关文章:

mysql - ILIKE 字符串中的搜索仅适用于其第一部分?

jquery - Ruby on Rails 网站 : Adding/Removing Active Class to Navbar

ruby-on-rails - 无法让 RSpec View 规范通过

ruby-on-rails - 为什么carrierwave会导致NameError: uninitialized constant Micropost::PictureUploader错误?

ruby-on-rails - 使用 rails 查找空的 Postgres json 子数组

css - 如何在 Rails 5 应用程序中使用 Bootstrap 4 Gem 修改默认外观

ruby-on-rails - Rails 5,Rspec : Environment data not found in the schema

ruby-on-rails - Vue.JS 和 Rails-UJS/Jquery-UJS 冲突 - Vuex 突变不起作用

ruby-on-rails - 在Rails 5中显示表单验证错误

ruby-on-rails - Ruby Hash 包含单个键的额外值