简体   繁体   中英

rails user-defined custom columns

I am using Ruby on Rails 4 and 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.

How can I achieve these custom columns in Ruby on Rails and MySQL and still maintain all the ActiveRecord capabilities, eg validation, etc?

Well you don't have much options, your best solution is using NO SQL database (at least for those classes).

Lets see how can you work around using SQL. You can have a base Course model with a has_many :attributes association. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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