I just realized I have some issues when deleting parent models.
I have this 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 you can guess if user.destroy is called and there is a conversation where the user is the recipient then it will raise PG::ForeignKeyViolation ERROR: update or delete on table conversations violates foreign key constraint...
To deal with this problem I'm planning to do the following:
user.rb
#this will solve the rails side of the problem
has_many :received_conversations, class_name: "Conversation", foreign_key: "recipient_id", dependent: :destroy
schema (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
Is this the right way to solve this issue?
dependent: :destroyon the rails side as well? The article says it could be deleted, but I would rather keep it.