Reputation: 335
I have two tables, "users" and "friendships", I'm trying to make a relationship so that a user can have a friendship with other users, so generate this model friendships with rails g model Friendship user:references friend:references status
in the model friendship.rb:
class Friendship < ApplicationRecord
belongs_to :user
belongs_to :friend,class_name: "User"
end
but at the time of creating the record it shows me the following error:
Friendship.create(user_id: 1, friend_id:2, id: 1)
(0.1ms) begin transaction
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
SQL (0.4ms) INSERT INTO "friendships" ("id", "user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["id", 1], ["user_id", 1], ["friend_id", 2], ["created_at", "2018-02-26 19:39:57.865042"], ["updated_at", "2018-02-26 19:39:57.865042"]]
(0.1ms) rollback transaction
Traceback (most recent call last):
1: from (irb):2
ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: main.friends: INSERT INTO "friendships" ("id", "user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?))
irb(main):003:0>
What could it be? I have Rails 5.1.5
Upvotes: 0
Views: 550
Reputation: 5213
Your Friendship model is set up correctly, but perhaps your migration is not. It should look like this:
class CreateFriendships < ActiveRecord::Migration[5.1]
def change
create_table :friendships do |t|
t.references :user, index: true, foreign_key: true
t.references :friend, index: true, foreign_key: { to_table: :users }
end
end
end
I've set this up in a new Rails 5.1.5 project and it is working for me:
>> User.create(name: 'First User')
>> User.create(name: 'Second User')
>> Friendship.create(user_id: 1, friend_id:2, id: 1)
(0.1ms) begin transaction
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
SQL (0.8ms) INSERT INTO "friendships" ("id", "user_id", "friend_id") VALUES (?, ?, ?) [["id", 1], ["user_id", 1], ["friend_id", 2]]
(0.8ms) commit transaction
#<Friendship id: 1, user_id: 1, friend_id: 2>
Incidentally, you should avoid assigning id numbers to non-persisted objects. Better to let the database handle that job. I would create a Friendship simply as:
>> Friendship.create(user_id: 1, friend_id: 2)
Upvotes: 2