2017-05-11 17 views
0

내 응용 프로그램에는 ServiceUser의 두 모델이 있습니다. 서비스에 드라이버이 지정되어있을 수 있습니다.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 

내 문제를이 내가없이 새로운 서비스를 만들려고 할 때

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

그러나 driver_id 이후 "0": 드라이버 내 params는 드라이버 "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를 사용하고 있습니다.

이 예외를 피하기 위해 내 모델 또는 마이그레이션을 어떻게 수정할 수 있는지 알고 싶습니다. 어떤 아이디어?

대단히 감사합니다.

답변

0

죄송합니다. 방금 해결책을 깨달았습니다. 내가 말하지 않은 무엇인가는 select 요소를 사용하여 드라이버에 들어가는 것입니다. 드라이버는 선택 사항이기 때문에 내가 추가하고 사용 "빈"하였다

<option value=""></option> 

문제가 해결 :

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

가 변경.

아무런 가치가 없으므로 질문을 삭제하는 것이 좋습니다.