Question

Please check my understanding of how recursive destroys work?

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.

models > blog.rb

class Blog < ActiveRecord::Base
  attr_accessible :description, :title, :user_id, :cover
  belongs_to :user
  has_many :posts, :dependent => :destroy
end

models > post.rb

class Post < ActiveRecord::Base
  attr_accessible :blog_id, :content_1, :type, :user_id, :media, :picture, :event_id
  belongs_to :blog
  belongs_to :user
end

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.

controllers > post_controller.rb

def destroy
    @post = Post.find(params[:id])

    # Delete Feed on the creation of the post
    if Feed.exists?(:content1 => 'newpost', :content2 => params[:id])
        @feeds = Feed.where(:content1 => 'newpost', :content2 => params[:id])
    @feeds.each do |feed|
        feed.destroy
end
end

@post.destroy
   respond_to do |format|
     format.html { redirect_to redirect }
     format.json { head :no_content }
   end
end

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.

Was it helpful?

Solution

I would suggest moving the custom Feed-deletion code into your Post model like do:

class Post
  before_destroy :cleanup

  def cleanup
    # Delete Feed on the creation of the post
    if Feed.exists?(:content1 => 'newpost', :content2 => id)
      @feeds = Feed.where(:content1 => 'newpost', :content2 => id)
      @feeds.each do |feed|
        feed.destroy
      end
    end
  end
end

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top