我有以下模型及其关联如下
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
一家公司可以有多个区域和分支机构。有一种情况是,在具有多个分支机构的公司中,将共享公司提供的相同服务。如何实现此方案。
如果你想重用Company
提供的每一个Service
,你可以简单地编写一个方法来访问它们:
class Branch < ActiveRecord::Base
belongs_to :region
...
def services
region.company.services
end
end
我不会与服务直接关联(在rails意义上),因为这将允许Branch
实例更改(添加/删除)公司提供的服务。
但是我会在Company
和Branch
之间添加关联,因为该区域看起来确实是一个简单的连接表,并且具有关联将美化代码:
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