我有三个模特
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))
endHiringTagApplication
class HiringTagApplication < ActiveRecord::Base
belongs_to :hiring_tag, dependent: :destroy
belongs_to :job_application
endJobApplication
class JobApplication < ActiveRecord::Base
has_many :hiring_tag_applications
has_many :hiring_tags, through: :hiring_tag_applications
end我要做的是:当我销毁HiringTag或JobApplication时,我希望删除HiringTagApplication中的相关数据,因为您会注意到,在HiringTag中有一个after_destroy可以执行回调,但我得到的错误是:
找不到HiringTagApplication和id=96453
96453不是id of HiringTagApplication,但它是job_application_id
我如何纠正这一点,以便可以删除该记录?
发布于 2017-07-12 07:05:45
不需要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也将被删除。
https://stackoverflow.com/questions/45050605
复制相似问题