[英]Rails 5: Add belongs_to association
我有两个表“ users”和“ friendships”,我试图建立一种关系,以便一个用户可以与其他用户建立友谊,因此使用rails g model Friendship user:references friend:references status
生成此模型友谊rails g model Friendship user:references friend:references status
在Friendship.rb模型中:
class Friendship < ApplicationRecord
belongs_to :user
belongs_to :friend,class_name: "User"
end
但是在创建记录时,它显示了以下错误:
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>
会是什么呢? 我有Rails 5.1.5
您的友谊模型已正确设置,但迁移可能未正确。 它看起来应该像这样:
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
我已经在一个新的Rails 5.1.5项目中进行了设置,它正在为我工作:
>> 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>
顺便说一句,您应避免将ID号分配给非持久对象。 最好让数据库处理该工作。 我将简单地创建一个友谊:
>> Friendship.create(user_id: 1, friend_id: 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.