0

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?

2
  • Check out this post on referential integrity and foreign key constraints for rails. It looks like you're spot on thus far. robots.thoughtbot.com/referential-integrity-with-foreign-keys Commented Jun 9, 2016 at 11:33
  • Thanks bkunzi01! I have one more question after reading the article. Would you heep dependent: :destroy on the rails side as well? The article says it could be deleted, but I would rather keep it. Commented Jun 9, 2016 at 12:08

1 Answer 1

1

You do not need to mention foreign_key relation in:

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

as you already maintain this relation in belongs_to. If you remove the above foreign key relation, dependent: :destroy will destroy your corresponding conversation records as well of the deleted user record let it be the recepient or sender

Sign up to request clarification or add additional context in comments.

2 Comments

SnehaT, I have one more model (notifications) that has the same setup like conversations, and there I call user.notifications since I wanna list them. So in that case does my solution work? And what about db side?
Yeah it will work for notifications model as well. If you delete any user, it will delete the corresponding notifications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.