【发布时间】:2017-10-10 10:44:45
【问题描述】:
我的应用程序有两个模型:Service 和 User。服务可能有或没有分配驱动程序。我已将其实现为:
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