我正在开发网上商店以获得经验。我坚持建模产品的关系。
这是我的榜样。 ( - > =" has_many"):
国家/地区 - >标签(供应商) - >收藏 - >产品
模特
class Country < ActiveRecord::Base
has_many :labels
has_many :collections, through: :labels
end
class Label < ActiveRecord::Base
belongs_to :country
has_many :collections
end
class Collection < ActiveRecord::Base
belongs_to :label
has_one :country, through: :label, source: :country
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :collection
has_one :label, through: :collection, source: :label
has_one :country, through: :label, source: :country
end
我应该使用类别或子类别的每个模型。实施例
Brazil/SuperLabel/NightCollection/SuperProduct
但是每个产品都应该有描述中的国家,标签和集合名称。例如
价格:100.0 $
国家:巴西
collection:NightCollection
标签:SuperLabel
我使用这种方法
Product.all.includes(:country, :label, :collection)
,但我认为这是错误的解决方案,而不是rails方式。
问题:
1)还有哪些其他解决方案?我如何在产品型号中获取产品的国家,产品标签和产品系列?我的解决方案是坏还是不好?也许是另一种方法或模型之间的另一种关系
2)控制器。我应该为国家,标签等使用单独的控制器,并创建具有嵌套属性的产品(使用创建的早期变体)或使用嵌套资源?如果我使用嵌套资源,那么这个规则Resources should never be nested more than 1 level deep.
最佳解决方案是什么?
1)例如
resources :countries do
resources :labels, only: [:new, :create]
end
resources :labels, only: [:index, :show, :edit, :update, :destroy]
resources :labels do
resources :collections, only: [:new, :create]
end
resources :collections, only: [:index, :show, :edit, :update, :destroy]
resources :collections do
resources :products, only: [:new, :create]
end
resources :products, only: [:index, :show, :edit, :update, :destroy]
我认为这有点大规模的方法 第二个解决方案:
resources :countries
resources :labels
resources :collections
resources :products
当我创建产品时,我将添加国家,标签等,我分别在国家控制器,标签控制器等中创建。我想要简单的管理面板,没有困难的链接。
什么是最好的方法以及每种方法中的缺陷?也许所有方法都不好,并存在另一种解决方案。
答案 0 :(得分:0)
Product.all.includes(:country, :label, :collection)
只需提取所有产品即可。您也可以通过键入Product.all.includes(:collection => [:label => :country])
(您不需要这些has_one
关联)来获取它,并且它提供与前一个完全相同的结果。结果我的意思不是所有产品,而是所有剩余的关联都渴望加载相同数量的查询。
关于模型关系,它再次取决于您的需求。您的关系声明不如数据库表和索引那么重要。任何has_one
或has_many
只是告诉ActiveRecord
,如何将model A
与model B
关联并最终获取数据。这里重要的是,您已经在使用includes
进行预先加载。