请检查我对递归销毁是如何工作的理解?
我有一个包含很多帖子的博客对象。帖子继续拥有一个新闻提要对象,该对象是在每次创建帖子时创建的。当我删除博客时,帖子也会被删除,但帖子上的新闻提要对象不会被删除,只留下“幽灵”新闻提要对象。
models > blog.rb
class Blog < ActiveRecord::Base
attr_accessible :description, :title, :user_id, :cover
belongs_to :user
has_many :posts, :dependent => :destroy
endmodels > 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控制器的销毁函数中有一段特殊的自定义代码,它调用自定义销毁newfeed。那是不会被调用的。
控制器> 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
endpost的销毁函数中的那段代码没有被调用,所以newfeed对象没有被销毁。我对依赖销毁功能的理解是错误的吗?
我特别希望避免在新闻提要和post对象之间创建belongs_to和has_many关系,因为新闻提要对象是由其他类型的用户操作触发的,比如与新用户加好友,或者创建新博客,这些操作通过content1变量中的新闻提要类型来区分。
发布于 2013-07-10 02:35:53
我建议将自定义Feed-deletion代码移动到您的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现在,如果@feed是空的,那么可能是存在问题?函数。但是将此代码移动到此回调函数将确保任何时候删除帖子时,关联的提要都会被删除。
在您的控制器中,只需像往常一样调用@post.destroy,其余的就会自行处理。
https://stackoverflow.com/questions/17555556
复制相似问题