现在我有一个用户模型和一个博客模型。
class User < ApplicationRecord
has_many :blogs, dependent: :destroy
end
class Blog < ApplicationRecord
belongs_to :user
end
=> Blog(id: integer, user_id: integer, content: text, created_at: datetime, updated_at: datetime, title: string)
=> User(id: integer, name: string, email: string, username: string, number: integer, password_digest: string, created_at: datetime, updated_at: datetime, admin: boolean)
我曾经有一个播放器模型(与用户模型几乎相同,除了电子邮件/密码),但摆脱它。但是当我尝试在heroku控制台上创建一个新博客时,它给了我这个错误:
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "blogs" violates foreign key constraint "fk_rails_eb906800d1"DETAIL: Key (user_id)=(13) is not present in table "players".
这是什么意思?
heroku日志
ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR: insert or update on table "blogs" violates foreign key constraint "fk_rails_eb906800d1"
DETAIL: Key (user_id)=(13) is not present in table "players".
class CreateBlogs < ActiveRecord::Migration[5.0]
def change
create_table :blogs do |t|
t.references :user, foreign_key: true
t.text :content
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :username
t.integer :number
t.string :password_digest
t.timestamps
end
end
end
class AddAdminToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :admin, :boolean, default: false
end
end
class AddTitleToBlogs < ActiveRecord::Migration[5.0]
def up
add_column :blogs, :title, :string
end
def down
remove_column :blogs, :title, :string
end
end