Understanding add references

Hello community,

I have the following question:

I have two kmigrations a user migration and a comment migration .

On the create_user migration, is the following code

add(:comment_id, references(:comments, on_delete: :delete_all) ,

Wouldn’t this delete the user if a comment is deleted?

Thanks in advance

Yes, although it’s quite unusual for the users table to reference the comments table. Usually it’s the other way around. In that case deleting a user deletes their comments.

In most real world user / comment situations, I would not use on_delete: :delete_all. Usually you just soft delete users.

I though that using the two way realtion can facilitate the users to like comments.

Also thank you
So

add(:comment_id, references(:comments, on_delete: :nothing)?

You’d just do add(:comment_id, references(:comments)). This will raise a constraint violation if you try to delete the comment without also handling the user, which is usually what you want with your main tables. If I actually want to delete something, I usually want to be forced to write the code to handle deleting associated entities. I don’t want it to automatically happen, and I don’t want nothing to happen either.

However for your specific use case, your proposed method would only allow the user to like a single comment ever. Usually for tracking likes you’d use a join table that has

create table(:user_comment_likes) do
  add(:user_id, references(:users, on_delete: :delete_all))
  add(:comment_id, references(:comments, on_delete: :delete_all))
end

In this case I am using :delete_all since the table is really just metadata. If I do actually go to the trouble of deleting a user or a comment, I definitely want all of the likes deleted too. That is a judgement call you’ll need to make though.

2 Likes

Thank you for clarifying my dilemma and also for showing me how to implement my functionality