I’ve a simple blog style system where a user can have many entries.
I’ve tried to delete all of a users entries by doing the following –
user = User.find_by_id(1)
user.entries.delete_all
This hasn’t succeeded in deleting the related entries, it has just set the user_id in that entry to nil –
<Entry id: 20, content: "test", user_id: nil, created_at: "2011-10-31 10:26:18", updated_at: "2011-10-31 10:26:18", attachment_id: nil, likes_count: nil, comments_count: nil>
A few questions, if you don’t mind –
How can I ensure that all entries with no owner are deleted, and that their related info is deleted also? Based on the example above – I’d like to remove the entry and it’s related comments
How should I have initially avoided this problem? I presume my user.entries.delete_all command was the wrong thing to do.
do you know the difference between
destroyanddeletein Rails? if you usedestroyRails will instantiate the records to remove first, and call all callbacks associated withdestroy(before, after, around and cascading to associations). you could therefore create aafter_destroycallback which destroys all user related data, entries etc. or you declare your has_many relationship with:dependent => :destroy, which automatically adds a callback to destroy all related items