ルームモデルがあります。Room.first.nr
各部屋には 6 つの出口 (北、東、南、西、上、下)があり、最初の部屋の北に部屋を移動するなどのことができるはずです。私が作成したモデルは次のとおりです。
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
ただし、レール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