0

ルームモデルがあります。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
4

2 に答える 2

1

競合する関連付け名があります (例:has_one :nrbelongs_to :nr)。次のようなものにする必要があります。

class Room < ApplicationRecord

  belongs_to :sr, class_name: 'Room'
  belongs_to :wr, class_name: 'Room'
  belongs_to :nr, class_name: 'Room'
  belongs_to :er, class_name: 'Room'
  belongs_to :dr, class_name: 'Room'
  belongs_to :ur, class_name: 'Room'

end

関係はまだ必要ないと思いますhas_one。もうこれだけで四方八方の部屋が取れるからbelongs_to

于 2016-02-09T20:57:19.130 に答える