Rails - 在销毁父级时删除has_many关系

时间:2017-07-12 07:01:18

标签: ruby-on-rails

我有3个模特

HiringTag

class HiringTag < ActiveRecord::Base
  attr_accessible :name, :staffroom_id
  validates :name, presence: true

  has_many :hiring_tag_applications
  has_many :job_applications, through: :hiring_tag_applications

  after_destroy { |application|
    HiringTagApplication.destroy(application.job_applications.pluck(:job_application_id))
end

HiringTagApplication

class HiringTagApplication < ActiveRecord::Base
  belongs_to :hiring_tag, dependent: :destroy
  belongs_to :job_application
end

在线招聘

class JobApplication < ActiveRecord::Base
  has_many :hiring_tag_applications
  has_many :hiring_tags, through: :hiring_tag_applications
end

我想要做的是:当我销毁HiringTagJobApplication时,我希望在HiringTagApplication中删除相关数据,因为您会注意到我有after_destroy 1}}内部HiringTag回调确实被执行但我得到的错误是:

  

无法找到id = 96453

的HiringTagApplication

96453不是id的{​​{1}},而是HiringTagApplication

如何更正此内容以便删除记录?

1 个答案:

答案 0 :(得分:1)

无需after_destroy,只需正确使用dependent: :destroy

class HiringTag < ActiveRecord::Base
  has_many :hiring_tag_applications, dependent: :destroy
end

class JobApplication < ActiveRecord::Base
  has_many :hiring_tag_applications, dependent: :destroy
end

&安培;将其从关联表中删除

class HiringTagApplication < ActiveRecord::Base
  belongs_to :hiring_tag
  belongs_to :job_application
end

现在,每当HiringTag或JobApplication被删除时,其关联的HiringTagApplication也将被删除