0

나는 레일 4.2을 사용하고 알 수없는 이유로 참조가이 방법으로 만든 오래된 시스템을 유지하고 있습니다 :레일 4.2 :로 참조 필드를 돌려 외래 키

t.references :credit_card, null: false 
    t.references :car, null: false 
    t.references :profile, null: false 

이 나를 위해 레지스터를 만들 수 있습니다를 예를 들어 잘못된 credit_card ids가있는이 모델입니다. 외래 키가 유효하지 않습니다.

생성 지수 마이그레이션 FK 년대로를 설정하지 않았고 전혀 확인하지 않았다

class AddIndexToRentals < ActiveRecord::Migration 
    def change 
    add_index :rentals, :credit_card_id 
    add_index :rentals, :car_id 
    add_index :rentals, :profile_id 
    end 
end 

가 어떻게 그 분야 외래 키를 만들 수 있습니다 만 존재 ID를 받아?

답변

0

마이그레이션에 외래 키를 추가하여 참조 된 레코드의 존재를 확인하고 마이그레이션을 생성 한 후 다음을 수행 할 수 있습니다.

class AddForeignKeyToRentals < ActiveRecord::Migration 
    def change 
    add_foreign_key :rentals, :credit_cards 
    add_foreign_key :rentals, :cars 
    add_foreign_key :rentals, :profiles 
    end 
end 

외래 키 열에없는 레코드가있는 경우이 마이그레이션을 실행할 수 없다는 점에 유의해야합니다. 또한 모델에 추가 존재 확인을 추가 할 수 있습니다.

validates :credit_card, :car, :profile, presence: true 

희망이 있습니다. :)