如何获得rails& activerecord来管理整个协会的状态

时间:2014-09-23 11:07:54

标签: ruby-on-rails activerecord ruby-on-rails-4

我有一个具有存档功能的应用程序,允许用户在删除对象后恢复它们。

核心功能已通过以下方式实施:

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_manybelongs_to操作。

所需规则如下:

  • 归档联系人时:如果联系人是与该组织关联的最后一个“活动”联系人,则该组织也应归档。
  • 恢复联系人时:如果关联的组织已归档,则还应恢复该组织,而不会恢复与该组织关联的任何其他归档联系人。
  • 归档组织时:它应归档所有关联的“有效”联系人。
  • 恢复组织时:应恢复所有已归档的联系人。

应该如何实现?

1 个答案:

答案 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