LoginSignup
2
0

More than 3 years have passed since last update.

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: main.follows~

Last updated at Posted at 2020-10-23

フォロー機能を実装するためにUserモデルと中間テーブルのRelationshipモデルを作成。

model/user.rb
.
.
  def follow(other_user)
    unless self == other_user
      self.relationships.find_or_create_by(follow_id: other_user.id)
    end
  end

こんな感じでfollowメソッドを作り、relation_controllerの該当アクション内で呼び出したところ、タイトルのエラーが出てきた。

テーブルがないと言われているけど必要なテーブルがあることはschemaファイルからも確認できたので混乱。

原因

原因としてはrelationshipsテーブルを作るときのmigrationファイルに問題があった

db/migrate/time_create_relationships.rb
class CreateRelationships < ActiveRecord::Migration[5.2]
  def change
    create_table :relationships do |t|
      t.references :user, foreign_key: true
      t.references :follow, foreign_key: true

      t.timestamps

    end
    add_index :relationships, [:user_id, :follow_id], unique: true
  end
end

こちらのfollow_idカラムを作成する部分、t.references :follow, foreign_key: trueのforeign_keyがtrueとなっている部分が原因でした。
foreign_keyがtrueになっているとid名と同じテーブルが存在するか、つまりありもしないfollowテーブルがあるかを確認してしまうため、エラーが吐き出されていたようです。

解決法としては該当部分に

db/migrate/time_create_relationships.rb

 t.references :follow,  foreign_key: { to_table: :users }

と参照するテーブルを記述することで正しく動作しました。

rails g model relationships follow:referencesとターミナルで自動作成されたマイグレーションファイルはデフォルトでforeign_key:trueとなるので気を付けたいところです。

2
0
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
0