2016-10-27 3 views
0

레일즈를 레거시 포스트그레스 데이터베이스와 함께 사용하고 있는데, 이는 마이그레이션이 없음을 의미합니다. 스키마는 별도로 정의됩니다.레일 및 포스트그레스의 기본 키를 가리 키지 않는 외래 키?

두 개의 테이블이 있습니다 : notificationnotification_type. notification_type 테이블에는 ID (기본 키)과 code 열이 있습니다. notification 테이블의 열에 notificiation_type 테이블의 code 열에 외래 키가 있습니다.

class Notification < ActiveRecord::Base 
    ... 
    belongs_to :notification_type, foreign_key: 'notification_type' 
    ... 

NotificationType : 나는 알림 모델을 만들 호출하면이 NOTIFICATION_TYPE의 ID 열이 아닌 코드 열로 만들려고 있기 때문에, 그것은 나에게 외래 키 오류를 제공

class NotificationType < ActiveRecord::Base 
    has_many :notifications 
end 

. 18

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "notification" violates foreign key constraint "notification_notification_type_fkey" DETAIL: Key (notification_type)=(18) is not present in table "notification_type".

는 ID,하지만 난 그것을 내가 association_foreign_key 값을보고 1 또는 2와 같은 것이 될 것입니다 코드를 사용해야하지만 그것은 단지 has_and_belongs_to_many 협회와 함께 작동 것으로 보인다. 단지 폐쇄

psql 프로그램은 :

Foreign-key constraints: "notification_notification_type_fkey" FOREIGN KEY (notification_type) REFERENCES notification_type(code)

는 기본적으로, 어떻게 레일이 기본 키를 사용하여 항상 내 데이터베이스에서 외래 키 관계를 존중하는 대신에받을 수 있나요

? id

belongs_to :notification_type, foreign_key: 'notification_type', primary_key: 'code' 

primary_key 기본값을하지만 당신은 당신이 원하는 무엇이든 사용할 수 있습니다

답변

3

그냥 않습니다.

has_many :notifications 연결에 대해 동일한 옵션을 지정해야합니다. has_many는 belongs_to와 완전히 연결되어 있다는 사실을 전혀 모르기 때문에 비표준 키도 사용하고 있는지 알아야합니다.

+0

나는 이미 이것을 시도했다. 어쨌든 나는 맹세 할 수 있었다. 나는 다시 시도해 보았다. 나는 어딘가에 어떤 것을 섞어 놓았어야한다. 정말 고맙습니다! – ssb