需要实现rails关联以共享相同的功能

时间:2017-10-04 08:32:25

标签: ruby-on-rails activerecord model-associations

我有以下模型及其关联如下

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

公司可以拥有多个地区和分支机构。有一种情况是,在拥有多个分支机构的公司中,将共享公司提供的相同服务。如何实施此方案。

1 个答案:

答案 0 :(得分:1)

如果您想重复使用ServiceCompany商品,只需编写一个方法来访问它们:

class Branch < ActiveRecord::Base
  belongs_to :region

  ...

  def services
    region.company.services
  end
end

我会避免与服务直接关联(在rails意义上),因为这将允许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