Topic: Handling enum-like values in ActiveRecord

Hello,

one of my model objects has a character-field containing one of 4 different chars. I would like to constrain the possible values to these 4 characters.

How should I model this so that the values are constrained in the model and in the database ?

Re: Handling enum-like values in ActiveRecord

You can add a validation to the model to make sure that the value is correct.

# in model
def validate
  unless %w[a b c d].include? foo
    errors.add :foo, "must be either a, b, c, or d."
  end
end

Railscasts - Free Ruby on Rails Screencasts

Re: Handling enum-like values in ActiveRecord

I guess this is the same as...

validates_inclusion_of    :usertype, :in => %w{ a, b, c, d }

Which datatype would the 'usertype' require ?

Re: Handling enum-like values in ActiveRecord

Woyzeck wrote:

I guess this is the same as...

validates_inclusion_of    :usertype, :in => %w{ a, b, c, d }

Yep, I forgot about that validation method.

Woyzeck wrote:

Which datatype would the 'usertype' require ?

A simple string/varchar column should be fine.

Railscasts - Free Ruby on Rails Screencasts

Re: Handling enum-like values in ActiveRecord

Thx, works smoothly.