【问题标题】:Rails ActiveRecord Relationship Invalid Foreign Key ErrorRails ActiveRecord 关系无效外键错误
【发布时间】:2017-12-21 14:41:13
【问题描述】:

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

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

Clubs 将始终在创建 Organizer 之后创建,因此 clubs 上的外键最初为 nil。

这是我在尝试创建组织者但尚未创建任何俱乐部时遇到的错误:

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"

提前感谢您的帮助!

【问题讨论】:

  • 您的错误可能来自其他地方。 Rails 正在寻找桌上俱乐部的 club_id。桌球俱乐部没有那个,它只有 id。
  • 感谢@DavidWeber 的输入!看起来错误是说外键 club_id (在组织者表上)不是俱乐部表上的有效主键(因为现在没有俱乐部)。虽然我将该外键设置为可选,但我认为我不会收到此错误。有什么想法吗?
  • 您能告诉我们您是如何创建 Organizer 记录的吗?
  • 您是自己编写架构还是使用迁移?我不确定 Rails 5,但我认为您需要 "clubs", ["club_id"], name: "index_clubs_on_organizer", using: :btree 或其他东西。
  • @DavidWeber 是的,这很奇怪,因为我正在使用迁移,但是我的应用程序的流程与我见过的其他人有点不同(因为您在它是父级(俱乐部)之前创建用户(组织者) ) 实际上是创建的)。谢谢,我会调查的!

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多