【问题标题】:belong_to association and ActiveRecord::InvalidForeignKey in Rails 5Rails 5中的belong_to关联和ActiveRecord::InvalidForeignKey
【发布时间】:2017-10-10 10:44:45
【问题描述】:

我的应用程序有两个模型:ServiceUser。服务可能有或没有分配驱动程序。我已将其实现为:

class User < ApplicationRecord
end

和:

class Service < ApplicationRecord
    has_and_belongs_to_many :users
    belongs_to :driver, class_name: "User", optional: true
end

请注意,由于特定服务可能有也可能没有驱动程序,因此我将关联标记为optional。而且我没有从User 模型到Service 的任何指针。 我有以下实现此关联的迁移:

class AddOPtionalDriverToService < ActiveRecord::Migration[5.0]
  def change
    add_reference :services, :driver, references: :users, index: true
    add_foreign_key :services, :users, column: :driver_id
  end
end

我运行迁移时架构的相关部分是:

create_table "services", force: :cascade do |t|
    t.string   "destination"
    ....
    t.text     "comments"
    t.index ["driver_id"], name: "index_tdy_requests_on_driver_id", using: :btree
  end
...
  add_foreign_key "tdy_requests", "users", column: "driver_id"
end

我的问题是,当我尝试在没有驱动程序的情况下创建新服务时,我的 params 包含驱动程序的 "0" 值:

Parameters: {"utf8"=>"✓",
  "authenticity_token"=>"kVC53huZYZxuF4akSiqkGkSvoo5p2f4dQ==", 
  "service"=>{
    "destination"=>"Some where", ... , 
    "driver_id"=>"0", 
    "comments"=>""}, 
  "commit"=>"Create Service"}

但由于 driver_id 为“0”,我得到以下异常:

PG::ForeignKeyViolation: ERROR: insert or update on 
table "services" violates foreign key constraint 
"fk_rails_15497e1c36" DETAIL: Key (driver_id)=(0) is 
not present in table "users"

这很有意义,但有趣的是,当我从 SQLite 迁移到 PostgreSQL 时,我发现了这一点,因为 它在 SQLite 上运行良好。至少该应用程序正在做我想做的事情。我正在使用 Rail 5.0.2。

我想知道如何修改我的模型或迁移以避免此异常。有什么想法吗?

非常感谢您。

【问题讨论】:

    标签: postgresql sqlite activerecord ruby-on-rails-5 belongs-to


    【解决方案1】:

    对不起。我刚刚意识到解决方案。我没有说的是我使用选择元素输入驱动程序。由于驱动程序是可选的,我正在添加和“空”使用:

    <option value="0"></option>
    

    改为:

    <option value=""></option>
    

    解决问题。

    我宁愿删除这个问题,因为它没有任何价值。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2021-11-30
      • 2017-10-19
      • 2010-10-06
      相关资源
      最近更新 更多