我有一个房间模型。每个房间有 6 个出口(北、东、南、西、上、下),我应该可以做一些事情,比如Room.first.nr
把房间带到第一个出口的北边。我制作的模型如下:
class Room < ApplicationRecord
has_one :nr, class_name: 'Room', foreign_key: :id
belongs_to :sr, class_name: 'Room'
has_one :er, class_name: 'Room', foreign_key: :id
belongs_to :wr, class_name: 'Room'
has_one :sr, class_name: 'Room', foreign_key: :id
belongs_to :nr, class_name: 'Room'
has_one :wr, class_name: 'Room', foreign_key: :id
belongs_to :er, class_name: 'Room'
has_one :ur, class_name: 'Room', foreign_key: :id
belongs_to :dr, class_name: 'Room'
has_one :dr, class_name: 'Room', foreign_key: :id
belongs_to :ur, class_name: 'Room'
end
但是,当在 rails c 中执行此操作时
Room.create!(title:'sometitle', description:'somedescription', er: Room.first)
我得到这个:
ActiveRecord::RecordInvalid: Validation failed: Sr must exist, Wr must exist, Nr must exist, Dr must exist, Ur must exist
我也一直在玩,inverse_of
无济于事。
这是我的迁移:
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :title, null: false
t.text :description, null: false
t.integer :nr_id, null: true
t.integer :er_id, null: true
t.integer :sr_id, null: true
t.integer :wr_id, null: true
t.integer :ur_id, null: true
t.integer :dr_id, null: true
t.timestamps
end
add_index :rooms, :nr_id
add_index :rooms, :er_id
add_index :rooms, :sr_id
add_index :rooms, :wr_id
add_index :rooms, :ur_id
add_index :rooms, :dr_id
end
end