I am new to Ruby on Rails (which may soon be obvious) and I’m trying to figure out a model for the following data scenario. I have read several posts and searched Google at length, but I’m still confused.
I have 5 different tables with identical columns, except the value column has a different data type. They data is in 5 separate tables for a variety of good reasons, but think of it as data sharded across multiple tables.
logbook_strings (user_id, entry_id, field_id, value)
logbook_booleans (user_id, entry_id, field_id, value)
logbook_integers (user_id, entry_id, field_id, value)
logbook_decimals (user_id, entry_id, field_id, value)
logbook_datetimes (user_id, entry_id, field_id, value)
So here’s what the data would look like:
------------------------------------------------
| user_id | entry_id | field_id | value |
------------------------------------------------
| 1 | alpha1 | date | 2012-11-14 |
| 1 | alpha1 | duration | 1.2 |
| 1 | alpha1 | remarks | Nice job. |
------------------------------------------------
| 1 | alpha2 | date | 2012-11-13 |
| 1 | alpha2 | duration | 2.7 |
| 1 | alpha2 | remarks | Bad job. |
------------------------------------------------
Entry alpha1:
2012-11-14, 1.2, Nice Job.
Entry alpha2:
2012-11-13, 2.7, Bad job.
etc.
The reason I do this is so that I can have an infinitely flexible database. I can add a new field_id at any time to add a new field/feature to my app instead of doing a schema update to add yet another column to a wide logbook table.
So what I’m wondering, is there a way I can have a single ActiveRecord model in which I can reference all 5 of these tables?
After spending a few minutes trying to shoehorn this into a single ActiveRecord class, I don’t think it’s a great idea to use ActiveRecord for something like this. I see a few options:
If you must keep your schema, creating a separate model for each logbook table could be your best option.
If you can change your schema a bit, here’s an option:
You can use the
serializeclass method described here (cmd+f for ‘serialize’) to store your entries so instead of having many models, you just have two:LogbookandLogbookField. It might look something like this:Something to that effect. That way you retain most all the ActiveRecord niceties while still maintaining some of the “infinite-ness” of your schema design. However, adding/removing columns on a single table with migrations would probably prove easier than this even. Again, it depends on whether you can be flexible in your schema or not. Hope this helps.