Reputation: 1349
I recently came across an instance when I deleted a User from the database, but the index page for Posts broke because the User that wrote a specific post did not exist anymore.
This made me wonder whether it is good practice to always use :dependent => :destroy? Or is there a not-so-complicated alternative solution to not make the entire page break when the User is deleted? I guess it's more of a business decision, but I think I don't necessarily want to delete all the content when a User removes his account.
I suppose I could use something like
<%= link_to post.author.username unless post.author.blank? ...... %>
but that would make it a very tedious and messy task to have to include that in every line.
Any suggestions/tips on this matter?
Upvotes: 4
Views: 676
Reputation: 915
I think there are more than one possibilities. But it depends on what you want.
I dont like websites that are storing my personal data and do not delete it when I want them to delete it.
You could set a deleted_at attr to true if the user agrees with keeping his data. When the user is not okay with that, delete his profile and the comments.
Additionally you could override the username´s getter attribute for having a standard name for deleted users:
# author.rb
def username
return read_attribute :username if deleted_at.blank?
"unnamed"
end
Upvotes: 1
Reputation: 6623
You must either use dependent: :destroy
(or dependent: :delete
) or soft delete your users using deleted_at
column and then scoping the users so as to retrieve the non deleted ones.
You can write a SoftDeletable
module and include it in any model you want to soft delete or use one of these gems: https://www.ruby-toolbox.com/categories/Active_Record_Soft_Delete.
Upvotes: 2
Reputation: 138
Rather then deleting the user deactivate the user, this way you won't break any of the relationships and your data will remain consistent.
Upvotes: 6