Ruby on rails Rails ActiveRecord关系无效外键错误

Ruby on rails Rails ActiveRecord关系无效外键错误,ruby-on-rails,database,activerecord,ruby-on-rails-5,rails-activerecord,Ruby On Rails,Database,Activerecord,Ruby On Rails 5,Rails Activerecord,我是Rails新手(使用5.1),在设置ActiveRecord关联时遇到问题 组织者可以注册,然后创建一个俱乐部。一个组织者属于一个俱乐部(我想可能会有多个,但现在只期望一个是可以的)。俱乐部可以有很多组织者 俱乐部将始终在创建组织者后创建,因此俱乐部的外键最初为零 以下是在没有创建任何俱乐部的情况下尝试创建组织者时遇到的错误: ActiveRecord::InvalidForeignKey: ActiveRecord::InvalidForeignKey: PG::Forei

我是Rails新手(使用5.1),在设置ActiveRecord关联时遇到问题

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

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

以下是在没有创建任何俱乐部的情况下尝试创建组织者时遇到的错误:

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".
组织者:

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

提前感谢您的帮助

出于某种原因,您的代码试图将
0
值设置为
club\u id

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

Organizer.create!(
  #...
  club_id = nil
)

你的错误可能来自其他地方。Rails正在查找桌上俱乐部的俱乐部id。Table club没有这个,它只有id。谢谢@DavidWeber的输入!看起来错误是说外键club_id(在组织者表上)在clubs表上不是有效的主键(因为现在没有俱乐部)。虽然我将外键设置为可选,所以我认为不会出现此错误。有什么想法吗?你能告诉我们你是如何创建组织者记录的吗?你是在写模式还是在使用迁移?在rails 5中我不确定,但我认为您需要一个
“clubs”[“club_id”]、名称:“index_clubs_on_organizer”,使用::btree
或其他东西。@DavidWeber是的,这很奇怪,因为我在使用迁移,但我的应用程序的流程与我见过的其他应用程序有点不同(因为您在创建用户(组织者)之前创建了它的父(俱乐部)实际上是创建的)。谢谢,我会调查的!
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"
Organizer.create!(
  #...
  club_id = nil
)