Rails ActiveRecord关系无效外键错误

时间:2017-12-21 14:41:14

标签: ruby-on-rails database activerecord ruby-on-rails-5 rails-activerecord

我是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

俱乐部:

class Club < ApplicationRecord
    has_many: organizers
end

架构:

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"

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

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

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