ruby-on-rails – 如何在不调用依赖的情况下销毁Rails模型::关联
发布时间:2020-12-17 01:48:06 所属栏目:百科 来源:网络整理
导读:有没有办法破坏Rails模型而不调用依赖的回调::关联中的destroy. 例: class Administration ActiveRecord::Base include IdentityCache attr_accessible :auto_sync,:response_rate_calc_state,:description,:year,:project_id,:season,:auto_async,:synchro
有没有办法破坏Rails模型而不调用依赖的回调::关联中的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 我想删除记录和附件文件,但不要调用回调来删除名单 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 链接:api docs on skip_callback (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |