我有三个 activerecord 类:Klass、Reservation 和 Certificate 一个 Klass 可以有许多预订,每个预订可能有一个证书
定义如下...
class Klass < ActiveRecord::Base
has_many :reservations, dependent: :destroy, :autosave => true
has_many :certificates, through: :reservations
attr_accessible :name
def kill_certs
begin
p "In Kill_certs"
self.certificates.destroy_all
p "After Destroy"
rescue Exception => e
p "In RESCUE!"
p e.message
end
end
end
class Reservation < ActiveRecord::Base
belongs_to :klass
has_one :certificate, dependent: :destroy, autosave: true
attr_accessible :klass_id, :name
end
class Certificate < ActiveRecord::Base
belongs_to :reservation
attr_accessible :name
end
我希望能够通过调用 Klass#kill_certs(上图)来删除/销毁 klass 控制器中特定 klass 的所有证书
但是,我收到一条消息异常:
"In RESCUE!"
"Cannot modify association 'Klass#certificates' because the source
reflection class 'Certificate' is associated to 'Reservation' via :has_one."
我(还尝试将预订类更改为“has_many :certificates”,然后错误是...
"In RESCUE!"
"Cannot modify association 'Klass#certificates' because the source reflection
class 'Certificate' is associated to 'Reservation' via :has_many."
奇怪的是,我可以从控制台执行 Klass.first.certificates 并检索第一类的证书,但我不能在不创建错误的情况下执行 Klass.first.certificates.delete_all。我错过了什么吗?
这是唯一的方法..
Klass.first.reservations.each do |res|
res.certificate.destroy
end
谢谢你的帮助。