【发布时间】: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