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

Create a User model and an intermediate table Relationship model to implement the follow function.

model/user.rb


.
.
  def follow(other_user)
    unless self == other_user
      self.relationships.find_or_create_by(follow_id: other_user.id)
    end
  end

When I created a follow method like this and called it in the corresponding action of relation_controller, an error in the title appeared.

It is said that there is no table, but I was confused because I could confirm from the schema file that there was a necessary table.

Cause

The cause was a problem with the migration file when creating the relationships table

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

This was caused by the part that creates the follow_id column, the part where foreign_key of t.references: follow, foreign_key: true is true. If foreign_key is true, it will check if the same table as the id name exists, that is, if there is a follow table that does not exist, so it seems that an error was thrown out.

As a solution, in the relevant part

db/migrate/time_create_relationships.rb



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

It worked correctly by writing a table that references.

Please note that the migration file automatically created in the terminal with rails g model relationships follow: references defaults to foreign_key: true.

Recommended Posts

ActiveRecord :: StatementInvalid (SQLite3 :: SQLException: no such table: main.follows ~
[Android] no such table error solution
ActiveRecord :: StatementInvalid: SQLite3 :: BusyException: database is locked
RSpec gives ActiveRecord :: StatementInvalid: Could not find table