我有一个使用 PostgreSQL 的 Rails 4 应用程序。我的应用程序提供了一张 table 列表。每张 table 可以有一种或多种颜色(蓝色、红色、绿色等...)
给定一张 table 模型,存储每张 table 可用颜色的最佳方法是什么?
我可以做类似 Desk.color_options 的事情,只得到一个列表,但如果我想显示所有红色的 table ,我将无法有效地对 table 记录进行排序。
最佳答案
我可能会做这样的事情来开始:
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
如果你想找到所有的 table :
Product.all
如果你只想要红色的 table :
Product.by_variant(Variant.by_attr('color', 'red'))
关于ruby-on-rails - 推荐用于存储颜色选项的数据库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941247/