2014-09-23 43 views
0

我有一个具有存档功能的应用程序,允许用户在删除对象后恢复它们。如何让rails和activerecord在关联中管理状态

的核心功能已经实现下列要求:

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 

然而,支持需要被添加为“级联”跨越has_manybelongs_to协会archiverestore行动。

的期望的规则如下:

  • 当接触被归档:如果联系人关联到组织,则组织还应当存档的最后一个“有效”接触。
  • 当联系人恢复:如果相关机构存档那么它也应该恢复,无需恢复相关的组织中的任何其它归档的联系人。
  • 组织归档时:它应该归档所有关联的“活动”联系人。
  • 组织恢复时:它应该恢复所有存档的联系人。

这应该如何实现?

回答

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 
+0

感谢您花时间帮助解决这个问题。我还没有尝试过,但看起来可能会有一个问题,即使用多个归档联系人还原联系人和归档组织。如果您从存档组织中恢复联系人,contact.restore会调用调用'contacts.update_all(:archived => false)'的'organisation.restore'。看起来这会恢复该组织内的所有已存档联系人,这不是预期的结果。有关如何避免这种情况的任何想法?我会更新这个问题以使其更清楚。 – tommarshall 2014-09-23 13:27:29

+0

是的,这是一个错误。通过增加一个附加参数来更新答案。参数名称不理想。也许你只需将'organisation.restore(all:false)'调用替换为'organisation.update(archived:true)' – 2014-09-23 13:54:15