postgresql - rails foreign key setup with AR and postgres -
i realized have issues when deleting parent models.
i have setup:
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"
schema (postgres db)
add_foreign_key "conversations", "users", column: "recipient_id" add_foreign_key "conversations", "users", column: "sender_id"
as can guess if user.destroy
called , there conversation user recipient raise pg::foreignkeyviolation error: update or delete on table conversations violates foreign key constraint...
to deal problem i'm planning following:
user.rb
#this solve rails side of problem has_many :received_conversations, class_name: "conversation", foreign_key: "recipient_id", dependent: :destroy
schema (db):
#this solve db side of problem add_foreign_key "conversations", "users", column: "recipient_id", on_delete: :cascade add_foreign_key "conversations", "users", column: "sender_id", on_delete: :cascade
is right way solve issue?
you not need mention foreign_key relation in:
has_many :conversations, foreign_key: "sender_id", dependent: :destroy
as maintain relation in belongs_to. if remove above foreign key relation, dependent: :destroy destroy corresponding conversation records of deleted user record let recepient or sender
Comments
Post a Comment