私のアプリケーションには、Service
とUser
という2つのモデルがあります。サービスにドライバが割り当てられているかどうか。belongs_to関連とActiveRecord :: InvalidForeignKey in Rails 5
class User < ApplicationRecord
end
と:特定のサービスまたはドライバを有していてもいなくてもよいので、私はoptional
としてアソシエーションをマークしていることを
class Service < ApplicationRecord
has_and_belongs_to_many :users
belongs_to :driver, class_name: "User", optional: true
end
注私は、これを実装しています。そして、私は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
私のスキーマの関連部分Iは、マイグレーションを実行したときには、次のとおりです。
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のと罰金働いていたので、私はこれを発見したということです。少なくともアプリケーションは私がやりたいことをやっていました。レール5.0.2を使用しています。
この例外を回避するためにモデルや移行をどのように変更することができますか。何か案は?
ありがとうございます。