我有一个Book
模型,我有一个User
模型。我正在尝试在author_id
表中创建一个名为books
的新列,该列实际上是users
表的外键。
我关注了this article by Joshua Frankel。但是我遇到了以下错误
activeRecord :: InvalidForeignKey:PG :: ForeignKeyViolation:错误`
我正在使用Rails4.2
db / migrate / 20191112111409_add_author_to_books.rb:
class AddAuthorToBooks < activeRecord::Migration
def up
add_reference :books,:author,references: :users,index: false
commit_db_transaction
add_index :books,:author_id,algorithm: :concurrently
add_foreign_key :books,:users,column: :author_id
end
def down
remove_column :books,:author_id
end
end
app / models / book.rb:
class Book < activeRecord::Base
belongs_to :author,class_name: :User,foreign_key: :author_id
end
app / models / user.rb:
class User < activeRecord::Base
has_many :books,foreign_key: :author_id
end
Rails控制台中的错误:
> user = FactoryBot.create(:user)
> book = FactoryBot.create(:book)
> book.author = user
> book.save
activeRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "books" violates foreign key constraint "fk_rails_13be98de92"
DetaIL: Key (author_id)=(1) is not present in table "users".
: UPDATE "books" SET "author_id" = $1,"updated_at" = $2 WHERE "books"."id" = $3
from ~/.ruby-gemset/ruby/2.3.0/gems/activerecord-4.2.11.1/lib/active_record/connection_adapters/postgresql_adapter.rb:602:in `exec_prepared'
Caused by PG::ForeignKeyViolation: ERROR: insert or update on table "books" violates foreign key constraint "fk_rails_13be98de92"
DetaIL: Key (author_id)=(1) is not present in table "users".
from ~/.ruby-gemset/ruby/2.3.0/gems/activerecord-4.2.11.1/lib/active_record/connection_adapters/postgresql_adapter.rb:602:in `exec_prepared'
>