sorry if this question has been asked before, I searched but wasn’t sure on the proper name for what I’m looking for.
I’m pretty much a newcomer to rails and development in general, I’ve done some hacky programming but I wouldn’t say I know what I’m doing. I’ve always been at a loss on how to define “types” in my Rails models and in databases in general.
For example, say I have a model “Car” and it has the property “Colour”, where Colour is chosen from a known set rather than an RGB value or whatever. Something tells me that there should be another table (and associated model) for Colour and then have some kind of relationship between the two, but which relationship is appropriate? A car doesn’t BELONG to its colour, or vice versa.
Or of course I could just store an integer and look it up in code, but this feels wrong to me.
What did I miss? 🙂
Color may be a complex object or may be a very simple one, depending on what you need.
For simple you’ll just have a column in cars named
color, and override the reader method to return whichever color format you desire, like so.If we’re talking about complex case, then it’s different. You should then have a separate model called Color. Then
Carwouldbelongs_to :colorlike thenduks said above. It would be more semantically correct to sayCar has_one :colorbut then you’re forcing colors table to storecar_idwhich would be kind of backwards. In our case, Car will be storingcolor_id. So make sure you make a migration that addscolor_idto tablecars.Then you should create the migration for
colorstable, which would includeid,titleandcodefor example, and which you’d have to pre-populate yourself using rails seeding stuff. (see http://railscasts.com/episodes/179-seed-data)