如何破坏Rails模型而不调用依赖::对关联的破坏

时间:2014-04-30 09:22:30

标签: ruby-on-rails ruby file postgresql callback

有没有一种方法可以在没有为关联中的dependent: :destroy调用回调的情况下销毁Rails模型。

示例:

class Administration < ActiveRecord::Base
  include IdentityCache

  attr_accessible :auto_sync, :response_rate_calc_state, :description,
    :year, :project_id, :season, :auto_async, :synchronized_at

  has_many :report_distributions 
  has_many :rosters, dependent: :destroy

  before_destroy :delete_file

  attr_accessible :file

  has_attached_file :file,
      path: ":class/:id_partition/:basename.:extension",
      storage: :s3,
      bucket: S3Config::AWS_BUCKET_MODELS,
      s3_credentials: {
          access_key_id: S3Config::AWS_ACCESS_KEY_ID_MODELS,
          secret_access_key: S3Config::AWS_SECRET_ACCESS_KEY_MODELS
      },
      s3_permissions: 'authenticated-read',
      s3_protocol: 'https',
      s3_storage_class: :reduced_redundancy

  def authenticated_url(style = nil, expires_in = 10.seconds)
    file.s3_object(style).url_for(:read, secure: true, expires: expires_in).to_s
  end

  def delete_file
    file.s3_object(nil).delete if self.file?
  end

# ...

所以当我打电话时

Administration.find(id).destroy

我想删除记录和附件文件,但不要调用回调来删除rosters

has_many :rosters, dependent: :destroy

-

PS我不想禁用has_many :rosters, dependent: :destroy。我只需要临时禁用回调。

2 个答案:

答案 0 :(得分:12)

您可以按照原样保持关联,并通过以下方式之一跳过回调:

1。使用delete代替销毁won't fire callbacks

Administration.find(id).delete

2。使用skip_callback方法(在此blog post中找到):

 Administration.skip_callback(:destroy, :bofore, :action_you_need_to_disable)
 #then safely destroy without firing the action_you_need_to_disable callback
 Administration.find(id).destroy

3。或者甚至更好,如果你已经知道何时需要跳过回调,你可以这样做:

class Admistration < ActiveRecord::Base
  has_many :rosters, dependent: :destroy
  skip_callback :destroy, :before, :action_you_need_to_disable, if: -> { #conditions }
end

链接:api docs on skip_callback

答案 1 :(得分:0)

您想使用dependent: :nullify

所以,它看起来像这样:

has_many :rosters, dependent: :nullify