我喜欢软件中的modularity,并据此创建模型。我想你会从这个想法中受益,所以我会为你解释一下:
模型
我喜欢保留模型以使模型具有可扩展性 - 这样您就可以添加 1,000,000 个项目,并且仍然让它以正确的方式工作。
为此,我们有“孤岛”数据库(我不确定这是否是正确的术语),然后围绕它有“参考”模型。
“筒仓”数据库/模型基本上存储静态数据(例如products 或users)。参考数据库/模型基本上为silo 数据库提供了更多范围 - 例如将options 添加到products 或profile 用于users。
在你的情况下,我肯定会这样做:
#app/models/product.rb
Class Product < ActiveRecord::Base
has_many :options, as: :optable do
def colours
where name: "colour"
end
end
end
#app/models/option.rb
Class Options < ActiveRecord::Base
belongs_to :optable, polymorphic: true
end
架构:
#products
id | name | SKU | stock | etc | etc | created_at | updated_at
#options
id | optable_type | optable_id | name | value | created_at | updated_at
--
协会
这是一个polymorphic association(因此您可以将options 模型与其他不相关的模型一起使用):
这意味着您可以拨打电话:
@product = Product.find params[:id]
@product.options #-> returns all `Option` records for `product` (`price`, `size`, `etc`)
如果你设置正确,你应该可以这样做:
#config/routes.rb
resources :products, only: :show #-> domain.com/products/14
#app/controllers/products_controller.rb
class ProductsController < ActiveRecord::Base
def show
@product = Product.find params[:id]
end
end
#app/views/products/show.html.erb
<%= @product.name %>
<% @product.options.each do |option| %>
<%= option.size %>
<%= option.price %>
<%= option.colour %>
<% end %>
如果您想调用product 的colour 选项,您可以这样做:
@product = Product.find params[:id]
@product.options.colours #-> will output all colours for the product
注意事项
我的代码的主要警告之一是我提供的options 没有以任何方式结构化。如果您想为产品提供特定的set 选项(例如为特定产品提供size、colour、quantity,您可能希望在Option 模型中使用self-referential association,如果你愿意,我可以做