I’m currently building a Rails app, and I’m trying to make sure I don’t make any big mistakes now in the database design (MySQL) that will haunt me down the road.
Currently I have a bunch of fields in various tables that reference simple constant data. For example, one of my tables is called rates and it’s fields are
id, amount and unit, with unit being per hour / day / week / month.
These values will not change, and instead of using a reference table I just used a single CHAR to represent the values, so hour would be 'h', day would be 'd', week would be 'w' and so on. I figured this would make the database more human friendly and limit the possibility of IDs changing somehow and all the data being corrupted because of it.
Does this seem like a reasonable approach, or am I missing some potential pitfall?
If it were up to me I would use a lookup table which contains key/value pairs, where the value is anything you want it to be. Something like this:
Then, in any tables where you need to reference a rate, simply use the id which correlates to the rate you are interested in, lets add a few rows:
Now, if you have a table which needs a reference to rate you would this:
The nice thing about this approach, if you ever decide you want to use just the first letter to identify a rate_type, you simply need to update the
lookup_rate_typetable:Even though you changed the name value (within a context you understand, second became s), any tables storing a relation to the value, will remain unchanged.
With this solution you can add as many rows as you need to the lookup table, vs having to run an alter statement just to add an enum, which can be painful if dealing with a large table.
The only drawback with this solution is you will probably need to use class constants to allow your application code access to the int values so you can conduct CRUD ops according to your business logic, something like:
Also, if you wanted to, when dealing with a small list of constants you can forgo the lookup table altogether and deal only with class constants. The drawback here is you will have to know the id when looking for specific data, vs using a query:
These are scenarios I have come across in dealing with a multitude of different applications, and have found the lookup table and/or class constants to be the best solution.