我有一个具有存档功能的应用程序,允许用户在删除对象后恢复它们。
核心功能已通过以下方式实施:
class Contact < ActiveRecord::Base
belongs_to :organisation
default_scope { where(:archived => false) }
def self.archived
unscoped.where(:archived => true)
end
def archive
update(:archived => true)
end
def restore
update(:archived => false)
end
end
class Organisation < ActiveRecord::Base
has_many :contacts
default_scope { where(:archived => false) }
def self.archived
unscoped.where(:archived => true)
end
def archive
update(:archived => true)
end
def restore
update(:archived => false)
end
end
但是,需要添加支持,以便在archive
restore
关联中“级联”has_many
和belongs_to
操作。
所需规则如下:
应该如何实现?
答案 0 :(得分:2)
class Contact < ActiveRecord::Base
belongs_to :organisation
default_scope { where(:archived => false) }
def self.archived
unscoped.where(:archived => true)
end
def archive
update(:archived => true)
organisation.archive(all: false) if organisation.contacts.archived.count == organisation.contacts.count
end
def restore
update(:archived => false)
organisation.restore(all: false) if organisation.archived
end
end
class Organisation < ActiveRecord::Base
has_many :contacts
default_scope { where(:archived => false) }
def self.archived
unscoped.where(:archived => true)
end
def archive(all: true)
update(:archived => true)
contacts.update_all(:archived => true) if all
end
def restore(all: true)
update(:archived => false)
contacts.update_all(:archived => false) if all
end
end