2017-10-04 89 views
0

我有以下型号及其协会如下需要实现共享相同的功能的轨道协会

class Region < ActiveRecord::Base 

    belongs_to :company 
    has_many :branches 

    validates :region_name, presence: true 
end 

class Branch < ActiveRecord::Base 
    belongs_to :region 

    validates :branch_name, presence: true 
    validates :branch_name, uniqueness: true 
end 

class Service < ActiveRecord::Base 
    belongs_to :company 
end 

class Company < ActiveRecord::Base 
    has_many :regions 
    has_many :services 

    validates :name, presence: true 
    validates :name, uniqueness: true 

    after_save :toggle_services, if: :status_changed? 

    def toggle_services 
    self.services.each do |service| 
     service.update_attributes!(status: self.status) 
    end 
    end 
end 

,公司可以有多个区域和分支机构。有一种情况,在一家拥有多家分支机构的公司将会共享公司提供的相同服务。这种情况将如何实施。

+0

我不完全得到了这个问题。看起来分支机构总是能够获得公司提供的所有服务,因为公司的服务是否与分支机构共享尚无区别。或者正在模拟我刚刚描述的缺乏具体解决方案的问题? – ulferts

+0

让我们以银行为例,就像银行有多个分行,但通常他们在每个分行都提供相同的服务,所以应该如何在模型层面完成这个工作,有没有办法通过关联来实现。 – Nikhil

回答

1

如果你想重用每ServiceCompany报价,你可以简单地写一个方法来访问它们:

class Branch < ActiveRecord::Base 
    belongs_to :region 

    ... 

    def services 
    region.company.services 
    end 
end 

我会从具有直接关联避免(在轨检测)到服务,因为这将允许Branch实例更改(添加/删除)公司提供的服务。

但是我CompanyBranch之间添加关联的区域看起来是一个简单的连接表和具有该协会将美化代码:

class Branch < ActiveRecord::Base 
    belongs_to :region 
    belongs_to :company, through: :region 

    ... 

    delegate :services, 
      to: :company 
end 

class Company < ActiveRecord::Base 
    has_many :regions 
    has_many :branches, through: :regions 
    ... 
end