推荐的db模式用于存储颜色选项

时间:2017-01-30 16:52:40

标签: ruby-on-rails postgresql ruby-on-rails-4 database-design

我有一个使用PostgreSQL的Rails 4应用程序。我的应用程序提供了一系列办公桌。每张桌子可以有一种或多种颜色(蓝色,红色,绿色等......)

鉴于模型台,每张桌面存储可用颜色的最佳方法是什么?

我可以做像Desk.color_options这样的事情并且只有一个列表但是如果我想要显示所有颜色为红色的办公桌,我将无法有效地对桌面记录进行排序。

1 个答案:

答案 0 :(得分:3)

我可能会做这样的事情开始:

class Product < ApplicationRecord
  has_many :product_options
  scope :with_variant, -> (variant) {
    joins(:product_options).merge(ProductOption.by_variant(variant))
  }
end

class ProductOption < ApplicationRecord
  belongs_to :product
  belongs_to :variant
  validates :stock_level, numericality: 0..1000

  scope :by_variant, -> (variant) { where(variant: variant) }
end

class Variant < ApplicationRecord
  scope :by_attr, -> (attr_name, attr_value) { 
    where(attribute: attr_name, value: attr_value)
  }
end

如果你想找到所有办公桌:

Product.all

如果你只想要红色桌子:

Product.by_variant(Variant.by_attr('color', 'red'))
相关问题