【发布时间】:2017-11-03 13:02:17
【问题描述】:
我有四个相互关联的模型:餐厅、菜单、部分和菜肴。菜肴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
【问题讨论】:
标签: ruby-on-rails activerecord associations has-many-through