【问题标题】:Rails Destroy Dependency not calling destroy function?Rails Destroy Dependency 不调用销毁函数?
【发布时间】:2013-07-09 18:27:17
【问题描述】:

请检查我对递归销毁如何工作的理解?

我有一个包含很多帖子的博客对象。这些帖子继续有一个新闻源对象,每次创建帖子时都会创建该对象。当我删除博客时,帖子被删除,但帖子上的新闻源对象没有被删除,给我留下了“幽灵”新闻源对象。

模型 > blog.rb

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

模型 > 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 控制器的销毁函数中有一段特殊的自定义代码,它要求自定义销毁新提要。没有被调用。

控制器 > 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

帖子的destroy函数中的那段代码没有被调用,所以newfeed对象没有被销毁。我对依赖破坏功能的理解是错误的吗?

我特别想避免在新闻源和帖子对象之间创建belongs_to 和has_many 关系,因为新闻源对象是由其他类型的用户操作触发的,例如与新朋友交朋友或创建新博客,这会根据新闻源的类型进行区分它在 content1 变量中。

【问题讨论】:

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


    【解决方案1】:

    我建议将自定义 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,其余的会自己处理。

    【讨论】:

    • 我确实认为这会起作用,但我只是对 :dependent => 破坏 rails 功能的性质有点困惑。当 blog 使用这个依赖销毁所有属于它的帖子时,它不会调用位于 posts 控制器中的销毁函数吗?如果不是,那么 delete_all 和 destroy 有什么区别?唯一的区别是使用destroy,我可以调用像before_destroy这样的花哨的函数吗?
    • 唯一从控制器调用函数的是来自用户的传入请求。控制器按照 routes.rb 的指示响应这些 HTTP 请求。它们实际上仅用于处理客户端和服务器之间的通信。确实,任何不处理这种通信的处理(例如读取/解析实体、传递错误消息、响应请求)都不应该进入控制器,而应该是模型或助手(恕我直言)。
    • 因此,调用顺序——客户端向 /posts/1 发出 DELETE 请求,controller#destroy 方法处理此请求,并调用 Post 模型上的 destroy 方法(由 ActiveRecord 提供的方法)。 :dependent 指定的销毁调用不通过控制器路由,它直接进入关联的模型(同样,通过提供的 ActiveRecord 方法)。希望这是有道理的。以下是有关控制器、模型和视图所扮演角色的更多详细信息:betterexplained.com/articles/…
    • 非常感谢您的澄清
    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多