I have a blog object that contains a lot of posts. The posts go on to have a newsfeed object that is created every time a post is created. When I delete the blog, the posts are deleted, but the newsfeed objects on the posts are not being deleted, leaving me with 'ghost' newsfeed objects.

So when I call for a blog to be destroyed, it's picking up all the posts and destroying them. That's great! But I have a special piece of custom code in the post controller's destroy function that calls for custom destruction of the newfeeds. That's not being called.

That bit of code in the post's destroy function is not being called, so the newfeed objects are not being destroyed. Is my understanding of the dependency destroy functionality wrong?

I specifically would like to avoid creating a belongs_to and has_many relationship between newsfeeds and post objects, because newsfeed objects are triggered by other types of user actions, like friending someone new, or creating a new blog, differentiated by the type of newsfeed it is in the content1 variable.

Now, if @feeds is empty, then it's probably a problem with the exists? function. But moving this code to this callback function will ensure that anytime a Post is deleted, the associated feeds get deleted.

In your controller, just call @post.destroy as normal, and the rest will take care of itself.

I do think this will work, but I'm just a bit confused about the nature of the :dependent => destroy functionality of rails. When blog uses this dependency to destroy all the posts that belong to it, does it not call the destroy function located in the posts controller? If not, then what is the difference between delete_all and destroy? Is the only difference is that with destroy, I get to call fancy functions like before_destroy?
–
ays0110Jul 9 '13 at 18:39

The only thing that calls functions from the controller are incoming requests from users. Controllers respond to these HTTP requests as directed by routes.rb. They are really only meant to handle communication between the client and the server. Really, any processing that doesn't deal with this sort of communication (such as reading/parsing entities, delivering error messages, responding to requests) should not go in the controller, and should be the model or a helper (IMHO).
–
GoGoCarlJul 9 '13 at 19:28

1

So, order of calls -- client makes DELETE request to /posts/1, controller#destroy method handles this request, and calls the destroy method on the Post model (a method supplied by ActiveRecord). The destroy call specified by :dependent isn't routed through the controller, it goes directly to the associated model (again, via that supplied ActiveRecord method). Hope that makes sense. Here's more details on the roles that controllers, models, and views play: betterexplained.com/articles/…
–
GoGoCarlJul 9 '13 at 19:32