活动记录关联上的回调

| 我有一个具有has_many的休假批准模型:entries是否可以通过一种方法来销毁其中一个条目,以销毁其余条目?我也想发送一封电子邮件,但不要每次发送一封电子邮件。有没有办法观察整个收藏的变化?     
已邀请:
        回调可能不是一个好选择,因为:
class Entry < ActiveRecord::Base
  def after_destroy
    Entry.where(:vacation_id => self.vacation_id).each {|entry| entry.destroy}
  end
end
会产生一些不好的递归。 可能是您应该在控制器中执行此操作:
class EntriesController < ApplicationController
  def destroy
    @entry = Entry.find(params[:id])
    @entries = Entry.where(:vacation_id => @entry.vacation_id).each {|entry| entry.destroy}
    #send email here
    ...
  end
end
    
        您可以使用
before_destroy
回调。
class VacationRequest < ActiveRecord::Base
  has_many :entries
end

class Entry < ActiveRecord::Base
  belongs_to :vacation_request
  before_destroy :destroy_others
  def destroy_others
    self.vacation_request.entries.each do |e|
      e.mark_for_destruction unless e.marked_for_destruction?
    end
  end
end
在对任何重要内容使用代码之前,请先对其进行绝对测试,但它应该为您提供入门指南。     
        我认为这应该起作用:
class Entry < ActiveRecord::Base
  belongs_to :vacation_request, :dependent => :destroy

  # ...
end

class VacationApproval < ActiveRecord::Base
  has_many :entries, :dependent => :destroy

  # ...
end
应该发生的是,当一个条目被销毁时,关联的VacationApproval将被销毁,随后所有与其关联的条目将被销毁。 让我知道这是否适合您。     
        所以我最后要做的是
class VacationApproval < ActiveRecord::Base
  has_many :entries , :conditions => {:job_id => Job.VACATION.id }, :dependent => :nullify

class Entry < ActiveRecord::Base
  validates_presence_of :vacation_approval_id ,:if => lambda {|entry| entry.job_id == Job.VACATION.id} , :message => \"This Vacation Has Been Canceled. Please Delete These Entries.\"
接着
@entries.each {|entry| entry.destroy if entry.invalid? }
在我的控制器的索引动作中。 和
`raise \"Entries are not valid, please check them and try again ( Did you cancel your vacation? )\" if @entries.any? &:invalid?` 
在提交动作中 同时删除其他行的问题是,如果我的UI进行了10次Ajax调用以选择10行,并且在我第一次遇到9个未处理的404响应时将其全部删除,这是不希望的。 由于我不在乎它们会保留在此处,只要无法提交条目即可。 对我而言,这是最简单/最安全/递归友好的方式,但可能不是最佳方式。感谢你的帮助!     
        对任何好奇/寻求信息的人 我最终通过设置“假期批准”模型来解决此问题
class VacationApproval < ActiveRecord::Base
    has_many :entries , :conditions => {:job_id => Job.VACATION.id }, :dependent => :delete_all
end
和我的进入模型是这样的
class Entry < ActiveRecord::Base  
  after_destroy :cancel_vacation_on_destory
  def cancel_vacation_on_destory
    if !self.vacation_approval.nil?
      self.vacation_approval.destroy
    end
  end
end
使用:delete_all不会处理回调,只会删除它们     

要回复问题请先登录注册