Daniel Hoelbling-Inzko talks about programming
One thing that may be overlooked sometimes (I certainly did) is the ability of ActiveRecord to not only bind to properties but also to instance fields (yes, even private ones). This little feature came in very handy when I was looking for a way to persist a class based enumeration. I’ll tell you why in a minute.
First, I have Users that can be in one of 5 categories. None of which were important enough to warrant a foreign-key relationship modeling in the database, but I still wanted to encapsulate them in some sort of object to avoid doing string checking inside my code. The model looks like this:
I clearly didn’t want to have a Category table in my database, so I decided on creating the Category class while saving the Name property to the database.
Here is my implementation of the User.Category field:
[Field] private string category;public Category Category { get { return Category.GetCategoryByName(category); } set { category = value.Name; } }
As you can clearly see. My code is only dealing with Category objects (that can have implementations attached) while behind the scenes I only write the name of the category to the backing field. This way I get rid of magic strings inside my code while not having to burden my database with foreign key constraints.