Rails Destroy Dependency不调用destroy函数?

时间:2013-07-09 18:27:18

标签: ruby-on-rails rails-activerecord destroy object-lifetime

请检查我对递归破坏如何工作的理解?

我有一个包含大量帖子的博客对象。帖子继续有每次创建帖子时创建的新闻源对象。当我删除博客时,帖子被删除,但帖子上的新闻源对象没有被删除,留下了'ghost'新闻源对象。

模型> blog.rb

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

模型&gt; 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

因此,当我要求销毁博客时,它会收集所有帖子并销毁它们。那很棒!但是我在post控制器的destroy函数中有一个特殊的自定义代码,它要求自动销毁newfeeds。那不是被召唤的。

控制器&gt; 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

不会调用post的destroy函数中的那段代码,因此newfeed对象不会被销毁。我对依赖性破坏功能的理解是错误的吗?

我特别希望避免在新闻源和帖子对象之间创建belongs_to和has_many关系,因为新闻源对象是由其他类型的用户操作触发的,例如为新朋友提供服务或创建新博客,区别于新闻源的类型它位于content1变量中。

1 个答案:

答案 0 :(得分:2)

我建议将自定义Feed删除代码移动到Post模型中,如:

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

现在,如果@feeds为空,那么它可能存在问题吗?功能。但是将此代码移动到此回调函数将确保无论何时删除帖子,相关的订阅源都将被删除。

在您的控制器中,只需正常调用@ post.destroy,其余的将自行处理。