关于数据库:激活ActiveRecord关系无效的外键错误

Rails ActiveRecord Relationship Invalid Foreign Key Error

我是Rails的新手(使用5.1),并且无法设置ActiveRecord关联。

组织者可以注册,然后创建一个俱乐部。一个组织者属于一个俱乐部(我想可能有多个俱乐部,但现在可以期望只有一个)。俱乐部可以有许多组织者。

将始终在创建组织者之后创建俱乐部,因此,俱乐部上的外键最初为零。

这是在尝试创建组织者而没有创建任何俱乐部时出现的错误:

1
2
ActiveRecord::InvalidForeignKey:         ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  insert or update on table"organizers" violates foreign key constraint"fk_rails_bc04936880"
        DETAIL:  Key (club_id)=(0) is not present in table"club".

组织者:

1
2
3
4
class Organizer < ApplicationRecord
    belongs_to :club, optional: true
    #also put config.active_record.belongs_to_required_by_default = false in application.rb
end

俱乐部:

1
2
3
class Club < ApplicationRecord
    has_many: organizers
end

模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
create_table"clubs", force: :cascade do |t|
    t.string"full_name"
    t.string"urn"
    t.string"short_name"
    t.string"address1"
    t.string"address2"
    t.string"city"
    t.string"state"
    t.string"zip"
    t.string"website"
    t.string"phone"
  end

  create_table"organizers", force: :cascade do |t|
    t.string"first_name"
    t.string"last_name"
    t.string"email"
    t.datetime"created_at", null: false
    t.datetime"updated_at", null: false
    t.string"password_digest"
    t.string"remember_digest"
    t.boolean"superuser", default: false
    t.string"activation_digest"
    t.boolean"activated", default: false
    t.datetime"activated_at"
    t.string"reset_digest"
    t.datetime"reset_sent_at"
    t.bigint"club_id"
    t.index ["club_id"], name:"index_organizers_on_club_id"
    t.index ["email"], name:"index_organizers_on_email", unique: true
  end

  add_foreign_key"organizers","clubs"

在此先感谢您的帮助!


由于某种原因,您的代码尝试将0值设置为club_id

我建议在此属性中强制nil并观察是否仍然发生错误:

1
2
3
4
Organizer.create!(
  #...
  club_id = nil
)