【问题标题】:Best way to represent reference data in Active Record在 Active Record 中表示参考数据的最佳方式
【发布时间】:2017-01-16 09:59:02
【问题描述】:

假设我有一个可以具有任意数量属性的产品......并且这些属性仅限于特定选项。一个产品可以有(每个下面的有效选项):

  • 颜色
    • 红色
    • 蓝色
    • 绿色
  • 类别
    • 运动
    • 正式
    • 儿童
  • 防水
    • 是的
    • 没有

列表可以继续。反正有没有用一个表在活动记录中表示这个?我认为最好有一个看起来像这样的单一参考数据表:

create_table :attritubes do |t|
  t.string :name # Red, Blue, Green, Sports, Formal...
  t.string :field_type # Color, Category, Waterproof...
end

为每个属性都有一个模型似乎是一种浪费,因为它并没有真正做太多事情。在这种情况下,我有一个名为 Attribute 的通用模型,产品有很多吗?或者有没有办法让活动记录通过列来区分属性(构成这种语法):

belongs_to :color, class_name: :attribute, where(field_type: 'color')

在输入之后,它几乎看起来像一个范围......这是一个更好的方法吗?

【问题讨论】:

  • 使用多态关联怎么样?我不能完全确定确切的模型关系,但那里的“_type”字段似乎是用例的有力指标。

标签: ruby-on-rails activerecord data-modeling


【解决方案1】:

您可以为类似的属性创建一个表

create_table :attritubes do |t|
  t.string :color 
  t.string :category 
  t.boolean :waterproof
end

& 然后在枚举中获取数据,例如

enum color: { red:0, blue:1, green:2 }
enum category: { sports:0, formals:1, kids:2 }
enum waterproof: { no:0, yes:1 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多