有没有一种方法可以轻松有效地获取父模型的相应(子)模型,然后在模板中呈现它?我想知道如何使用和不使用连接
例如,考虑这 3 个表:
# ProductGroup is the highest parent
class ProductGroup < ActiveRecord::Base
attr_accessible :name, :merchant_id
has_many :product_items
has_many :product_group_selections
end
# ProductItem is a child of ProductGroup
class ProductItem < ActiveRecord::Base
attr_accessible :base_price, :name, :product_group_id
belongs_to :product_group
end
# ProductGroupSelection is a child of ProductGroup
class ProductGroupSelection < ActiveRecord::Base
attr_accessible :name, :price_extra, :product_attr_group_id, :product_item_id
belongs_to :product_group
has_many :product_group_selection_attrs
end
# ProductGroupSelectionAttr is a child of ProductGroupSelection
class ProductGroupSelectionAttr < ActiveRecord::Base
attr_accessible :name, :product_group_id
belongs_to :product_group_selection
end
我想要的是一个看起来像这样的数据结构(在 product_groups 中搜索 Mercer_id = 1 时)
merchant_id 1 => {
ProductGroup.name, ProductGroup.merchant_id,
ProductItems => [...],
ProductGroupSelections => {ProductGroupSelections.name, ProductGroupSelectionAttrs => [...]}
}
这样,我可以依次循环遍历所有组及其子模型,以使用 ERB 生成表单。
谢谢