LoginSignup
2
1

More than 3 years have passed since last update.

rails c が立ち上がらず大量の行のエラーが出る

Last updated at Posted at 2020-10-02

問題

中間テーブルを作成した後くらいにrails cでコンソールを立ち上げようとしたが、以下のようなエラーが出た

: Unknown key: :throught. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors (ArgumentError)

rails sも立ち上がらず。

結論

中間テーブルのアソシエーションが間違っていた。以下のように修正した後、db:migrate:resetで解決。

roomsテーブルとusersテーブルの中間テーブルとしてroom-usersテーブルがあったが、
アソシエーションを以下のように組んでしまっていた。
テーブルの関係がおかしいままdb:migrateされているので、db:migrate:resetでテーブルの削除と再作成、db:migrateを行うと解決した。

間違い

(roomモデル)
class Room < ApplicationRecord
  has_many :rooms, through: :room_users
  has_many :room_users
end
(userモデル)
  has_many :rooms, through: :room_users
  has_many :room_users

間違いが2つある。
1.記載順
has_many :room_usersと記述する前に、throughでroom_usersを使用している。
2.モデル名
roomモデルの中に自身とのアソシエーションを組んでいる。

修正後

(roomモデル)
class Room < ApplicationRecord
  has_many :room_users
  has_many :users, through: :room_users
end
(userモデル)
  has_many :room_users
  has_many :rooms, through: :room_users

rails sやrails cにアソシエーションがなぜ関係あるのか

consoleやローカルサーバーを立ち上げる時にデータベースやマイグレーションファイルを通過するため。
そのマイグレーションファイルないでエラーが出て、consoleやローカルサーバーが立ち上がらなかった。

以上です。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1