【发布时间】:2019-11-13 04:11:44
【问题描述】:
我有一个Book 模型和一个User 模型。我正在尝试在books 表中创建一个名为author_id 的新列,它实际上是users 表的外键。
我关注了this article by Joshua Frankel。但我收到以下错误
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR`
我正在使用 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'
>
【问题讨论】:
标签: ruby-on-rails ruby postgresql activerecord foreign-keys