如何触发:dependent =>破坏

时间:2012-04-05 07:49:12

标签: ruby-on-rails ruby-on-rails-3 dependent-destroy

我有两个模型,User和Image。

class User < ActiveRecord::Base
  has_many :images,:order => "created_at DESC", :dependent => :destroy, :conditions => "archive = 0"

  def destroy
    self.archive = 1
    self.deleted_at = Time.now
    self.save
  end 
end 


class Image < ActiveRecord::Base
 belongs_to :user , :counter_cache => true

 def destroy
  self.archive = 1
  self.deleted_at = Time.now
  self.save
 end   
end

现在,如果您看到上面的代码,我将覆盖模型中的destroy调用。不是当用户删除他的帐户时我想触发依赖=>销毁回调,以便我触发图像的破坏。

PS:我不想使用act_as_paranoid或其他一些插件。我需要触发依赖=>毁灭,因为我有一个非常深的复杂映射,如:

用户has_many图片,      has_many评论,      has_many喜欢,      has_many活动     还有一些类型的映射和更深的maping等。

2 个答案:

答案 0 :(得分:1)

你只需要模仿依赖的破坏。

在你的destroy方法中调用你的Image的所有destroy方法

class User < ActiveRecord::Base
  has_many :images,:order => "created_at DESC", :dependent => :destroy, :conditions => "archive = 0"

  def destroy
    self.archive = 1
    self.deleted_at = Time.now
    self.save
    self.images.each(&:destroy)
  end 
end 

答案 1 :(得分:0)

也许为了让事情变得更容易,您可以将归档模型和可归档模型的行为封装在模块中:

module Archivable
  def archive!
    self.archive = 1
    self.deleted_at = Time.now
    self.save
  end
end

module Archiver
  def destroy
    self.archive = 1
    self.deleted_at = Time.now
    archive_models!
    self.save
    freeze
  end

  def archive_models!
    archivable_models.each do |model|
      model_name = model.name.pluralize.downcase.to_s
      self.send(model_name).each { |m| m.archive! }
    end
  end

  def archivable_models
    ActiveRecord::Base.send(:subclasses).select { |m| m.method_defined?(:archive!) }
  end
end

class Image < ActiveRecord::Base
  include Archivable
  belongs_to :user, :counter_cache => true
end

class User < ActiveRecord::Base
  include Archiver 
  has_many :images,:order => "created_at DESC", :conditions => "archive = 0", :dependent => :destroy
  attr_accessible :name
end

这是一个漂亮 hack-ish实现,但它确实有效。如果您按照帖子中的描述添加评论模型,则只需将has_many语句添加到用户并在评论模型中包含Archivable:

class User < ActiveRecord::Base
  include Archiver 
  has_many :images,:order => "created_at DESC", :conditions => "archive = 0", :dependent => :destroy
  has_many :comments,:order => "created_at DESC", :conditions => "archive = 0", :dependent => :destroy
  attr_accessible :name
end


class Comment < ActiveRecord::Base
  include Archivable
  belongs_to :user, :counter_cache => true
end