views:

69

answers:

2

I've looked through similar questions but I'm still a little perplexed about something that seems to be a simple case in Rails.

Let's say I have a model class called Employee. One attribute of an employee is their security_clearance, which is a string that can be None, Some, or Full. No other values are valid. In other applications I'd probably represent this an Employees table that has a foreign key to the SecurityClearances table, which has exactly three rows. The SecurityClearances table has columns entitled code (e.g. SEC_CLEARANCE_NONE, SEC_CLEARANCE_SOME, ...) and value ("None", "Some", "Full").

How do I want to do this in Rails? Do I want has_one :security_clearance on Employee and belongs_to :employee on SecurityClearance? That doesn't seem to be quite right.

It seems nonoptimal to type out the string literals of None, Some, and Full everywhere, especially since the values to be displayed could change (for example, perhaps the string for the Some code will be change to be low clearance instead).


Update:

Now that I think about this some more, don't I really just want a belongs_to :security_clearance on Employee? That would do the trick, right? Employees need to know what their security clearance levels are, but security clearance levels have no tie to a particular employee.

+1  A: 

Take a look at this plugin: http://github.com/mlightner/enumerations_mixin/tree/master

It allows you to define this like has_enumerated :security_clearance, besides also caching the SecurityClearance model, etc.

Without the plugin, though, you're right about the relationships.

Eduardo Scoz
+1  A: 

Also check out the Enum Fields plugin from the GiraffeSoft folks: http://giraffesoft.ca/blog/2009/02/17/floss-week-day-2-the-enum-field-rails-plugin.html

chrisrbailey