2016-06-09 2 views
0

상위 모델을 삭제할 때 몇 가지 문제가 있음을 알았습니다.AR 및 포스트그레스로 외래 키 설정

나는이 설정이 있습니다

user.rb을

has_many :conversations, foreign_key: "sender_id", dependent: :destroy 

당신이 경우 추측 수 있듯이 conversation.rb

belongs_to :sender, class_name: "User", foreign_key: "sender_id" 
belongs_to :recipient, class_name: "User", foreign_key: "recipient_id" 

스키마 (포스트 그레스 DB)

add_foreign_key "conversations", "users", column: "recipient_id" 
add_foreign_key "conversations", "users", column: "sender_id" 

user.destroy i

user.rb

#this will solve the rails side of the problem 
has_many :received_conversations, class_name: "Conversation", foreign_key: "recipient_id", dependent: :destroy 

: 나는 다음을 수행 할 계획입니다이 문제를 해결하기 위해 다음이 PG::ForeignKeyViolation ERROR: update or delete on table conversations violates foreign key constraint...

을 올릴 것이다라는 사용자가 수신자 인 대화가 s의 스키마 (DB) :

#this will solve the DB side of the problem 
add_foreign_key "conversations", "users", column: "recipient_id", on_delete: :cascade 
add_foreign_key "conversations", "users", column: "sender_id", on_delete: :cascade 

이 문제를 해결하는 올바른 방법입니까?

+0

레일에 대한 참조 무결성 및 외래 키 제약 조건에 대해이 게시물을 확인하십시오. 당신이 지금까지 그 자리에있는 것처럼 보입니다. https://robots.thoughtbot.com/referential-integrity-with-foreign-keys – bkunzi01

+0

감사합니다. bkunzi01! 기사를 읽은 후 질문이 하나 더 있습니다. 레일 측에서'종속 : 파괴하라 '는 말을 들으시겠습니까? 그 기사는 삭제 될 수 있다고 말하고 있지만, 나는 그것을 유지하려고한다. –

답변

1

당신은에 foreign_key 관계를 언급 할 필요가 없습니다 :

has_many :conversations, foreign_key: "sender_id", dependent: :destroy 

을 이미 belongs_to에서이 관계를 유지한다. 위의 외래 키 관계를 제거한 경우 : : destroy는 삭제 된 사용자 레코드뿐만 아니라 해당 대화 레코드도 삭제합니다.

+0

SnehaT, 대화와 같은 설정을 가진 모델이 하나 더 있습니다. 목록을 만들고 싶기 때문에'user.notifications'를 호출합니다. 그렇다면 솔루션이 작동합니까? 그리고 db 측은 어떨까요? –

+0

그래, 알림 모델에도 잘 작동 할거야. 사용자를 삭제하면 해당하는 알림이 삭제됩니다. – SnehaT