【问题标题】:need to implement rails association for sharing same functionalities需要实现 Rails 关联以共享相同的功能
【发布时间】:2017-10-04 08:32:24
【问题描述】:

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

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

一家公司可以有多个地区和分支机构。有一种情况是,一家拥有多个分支机构的公司将共享公司提供的相同服务。这个场景将如何实现。

【问题讨论】:

  • 我还不太明白这个问题。看起来分支机构总是会获得公司提供的所有服务,因为公司的服务是否与分支机构共享尚无区别。还是我刚才描述的建模缺少您想要解决的确切问题?
  • 让我们以银行为例,就像一家银行有多个分支机构,但通常它们在每个分支机构都提供相同的服务,那么这应该如何在模型级别完成,有没有办法通过关联来做到这一点.

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多