我有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
我想要做的是:当我销毁HiringTag
或JobApplication
时,我希望在HiringTagApplication
中删除相关数据,因为您会注意到我有after_destroy
1}}内部HiringTag
回调确实被执行但我得到的错误是:
无法找到id = 96453
的HiringTagApplication
96453
不是id
的{{1}},而是HiringTagApplication
如何更正此内容以便删除记录?
答案 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也将被删除