【发布时间】:2015-03-01 21:46:45
【问题描述】:
我之前在模型上使用过dependent: :destroy 没有任何问题,但在 Rails 4.2 中我被卡住了。过去的用途主要是经典的 has_many belongs_to 模型。似乎#<ActiveRecord::Associations::CollectionProxy 引起了我的问题。
class Subject < ActiveRecord::Base
has_many :properties
has_many :values, :through => :properties
has_many :tags, :through => :properties
class Property < ActiveRecord::Base
belongs_to :subject
belongs_to :tag
belongs_to :value
class Value < ActiveRecord::Base
has_one :property
has_one :subject, :through => :property
has_one :tag, :through => :property
class Tag < ActiveRecord::Base
has_many :properties
has_many :subjects, :through => :properties
我的目标是
- 删除主题将删除所有关联的属性和值
- 删除属性将删除关联的值,使主题保持不变
- 或者,删除一个值将删除关联的属性,保持主题不变
我尝试在主题中的值行和值中的属性行上添加依赖破坏。它会删除属性,但不会删除值。我尝试将它放在属性中的值属性行和值行并得到相同的结果 - 它不会删除值。
然后我尝试before_destroy 过滤器并在尝试模型关联时遇到了相同类型的问题或ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR。然后我破解了它并让它工作:
# In Subject model
before_destroy :destroy_values
def destroy_values
# relations does not seem to work got the Values using a new query
#values.destroy_all
pids = values.pluck(:id)
Value.where(id:pids).destroy_all
end
# in Value model
before_destroy :destroy_property
def destroy_property
property.destroy
end
不知道发生了什么,尽可能多地阅读 dependent 并尝试 delete_all,以及我看到的所有其他事情,我不高兴!
是的,这是一个奇怪的模型,只是玩弄并试图复制“Whatit?” Rails 中的 Apple II 数据库,让您大开眼界。
【问题讨论】:
标签: ruby-on-rails activerecord