有没有一种方法可以销毁 Rails 模型,而无需为关联中的 dependent::destroy
调用回调。
例子:
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
。我只需要暂时禁用回调。
最佳答案
您可以保持关联不变,并通过以下方式之一跳过回调:
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
关于ruby-on-rails - 如何在不调用依赖 : :destroy on associations 的情况下销毁 Rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23384275/