Enumerations - Best Practivce

Hello,

What is the best way to to do enumerations of values that you want to use to provide values for a field. There are many cases where you want the user to choose from a list of values, but you really don't need a whole model to support. Yet, it should be flexible enough to able to be changed.

A simple example would be a gender field in a person record. There needs to be somewhere to store the 'male' and 'female' values to be used in a select field,
but we don't want to hard code these values because later we might add 'unknown' as an option, or change to 'boy' and 'girl'. With only two values it seems pointless to have a whole model dedicated to this, yet it still needs to be somewhat dynamic as the values could change.

What is the best practice for this type of data?

Matt

Hello,

What is the best way to to do enumerations of values that you want to use to provide values for a field. There are many cases where you want the user to choose from a list of values, but you really don't need a whole model to support. Yet, it should be flexible enough to able to be changed.

A simple example would be a gender field in a person record. There needs to be somewhere to store the 'male' and 'female' values to be used in a select field,
but we don't want to hard code these values because later we might add 'unknown' as an option, or change to 'boy' and 'girl'. With only two values it seems pointless to have a whole model dedicated to this, yet it still needs to be somewhat dynamic as the values could change.

What is the best practice for this type of data?

I don't know about best practice, but I often stick these in global vars, usually in the application.rb file or similar.

Walter

Don’t know what the best practice is, but the way I do it is in the model

class User < ActiveRecord::Base

UserGenders = {:male => 1, :female => 2}

end

Then from code I just do if user.gender_id == User::UserGenders[:male]

I do it in the model, too, and also validate that nothing else can get
in that column in the database:

  GENDERS = %w(Male Female)
  validates_inclusion_of :gender, :in => GENDERS

Guys,

Thanks for the feedback.

Would these approaches still be the way to go if you had a large-ish set of data,
say State names of Country Names?

Matt

Guys,

Thanks for the feedback.

Would these approaches still be the way to go if you had a large-ish set of data,
say State names of Country Names?

That would depend on whether you needed to have related data, like this country has these states or anything like that. At that point you might want to move this into YAML or similar. There's a Railscast about this IIRC.

Walter