简体   繁体   English

rails用户定义的自定义列

[英]rails user-defined custom columns

I am using Ruby on Rails 4 and MySQL. 我正在使用Ruby on Rails 4和MySQL。 I have three types. 我有三种类型。 One is Biology, one is Chemistry, and another is Physics. 一个是生物学,一个是化学,另一个是物理。 Each type has unique fields. 每种类型都有唯一的字段。 So I created three tables in database, each with unique column names. 所以我在数据库中创建了三个表,每个表都有唯一的列名。 However, the unique column names may not be known before hand. 但是,可能事先不知道唯一的列名称。 It will be required for the user to create the column names associated with each type. 用户需要创建与每种类型关联的列名。 I don't want to create a serialized hash, because that can become messy. 我不想创建序列化哈希,因为这可能会变得混乱。 I notice some other systems enable users to create user-defined columns named like column1, column2, etc. 我注意到一些其他系统使用户能够创建名为column1,column2等的用户定义列。

How can I achieve these custom columns in Ruby on Rails and MySQL and still maintain all the ActiveRecord capabilities, eg validation, etc? 如何在Ruby on Rails和MySQL中实现这些自定义列并仍然保持所有ActiveRecord功能,例如验证等?

Well you don't have much options, your best solution is using NO SQL database (at least for those classes). 那么你没有太多的选择,你最好的解决方案是使用NO SQL数据库(至少对于那些类)。

Lets see how can you work around using SQL. 让我们看看你如何使用SQL。 You can have a base Course model with a has_many :attributes association. 您可以拥有一个带有has_many:attributes关联的基础课程模型。 In which a attribute is just a combination of a key and a value. 其中属性只是键和值的组合。

# attributes table
|  id  |    key    |  value  |
|  10  | "column1" | "value" |
|  11  | "column1" | "value" |
|  12  | "column1" | "value" |

Its going to be difficult to determin datatypes and queries covering multiple attributes at the same time. 很难确定同时覆盖多个属性的数据类型和查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM