【问题标题】:How to destroy Rails model without calling dependent: :destroy on associations如何在不调用依赖的情况下销毁 Rails 模型::destroy on associations
【发布时间】:2014-06-16 13:10:10
【问题描述】:

有没有一种方法可以在不调用关联中 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。我只需要暂时禁用回调。

【问题讨论】:

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


    【解决方案1】:

    您可以保持关联不变,并通过以下方式之一跳过回调:

    1.使用delete而不是destroy,因为它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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多