多个HMT关联与顶级关联

时间:2017-11-03 13:02:17

标签: ruby-on-rails activerecord associations has-many-through

我有四个相互关联的模型:餐馆,菜单,部分和菜肴。菜肴have_and_belong_to_many部分最终位于关联链的最底部。在我的应用程序中,我经常需要多次参考菜的餐厅。

我知道要做到这一点,我需要创建一系列HMT关联。我的问题是,在餐馆和菜肴之间设置belongs_to关系以避免多次查询或离开是否理想?截至目前,这只是感觉很脏(可能只是我)。

class Restaurant < ApplicationRecord
  has_many :menus, dependent: :destroy
  has_many :dishes, through: :menus
end

class Menu < ApplicationRecord
  has_many :sections, dependent: :destroy
  has_many :dishes, through: :sections

  belongs_to :restaurant
end

class Section < ApplicationRecord
  belongs_to :menu

  has_and_belongs_to_many :dishes
end

class Dish < ApplicationRecord
  has_and_belongs_to_many :sections
end

1 个答案:

答案 0 :(得分:0)

根据您的用例,您提出的denormalization对我来说似乎是合理的。与往常一样,非规范化的性能提升必须与其引入的复杂性进行权衡,尤其是编写代码以确保菜肴所属的餐厅始终与其菜单所属的餐厅相同。

我想我的方法是:保留规范化的数据模型,直到遇到需要解决的实际性能问题。然后你可以考虑非规范化来解决它。

虽然您仍然拥有级联的HMT,但考虑编写代理人以使代码保持干净,就好像您有一个直接的餐厅 - 餐馆协会。我在想:

class Dish < ApplicationRecord
  delegate :restaurant, to: :section
end

class Section < ApplicationRecord
  delegate :restaurant, to: :menu
end

然后你可以这样做:

dish.restaurant
相关问题