Alex Rivera | Logout

Best place to store model specific constants in rails 3.1?

Asked 2011-11-06T10:08:33.387
22

I have a field type in a model called user which is an int in the db. The value of the int speficies the type of store it is. Example:

  • 0 = mom
  • 1 = dad
  • 2 = grand mother
  • and so on

I have several other fields like this so it's overkill to create association tables.

Instead of checking for those int values over the place in conditional statements in model and controller logic, is there a place in rails to store these constants.

So that I could do this from my models and controllers?

if myuser.type == MOM
elsif myuser.type == GRAND_MOTHER

EDIT: Solution I went with at the end:

In model:

  # constants
  TYPES = {
    :mom => 0,
    :dad => 1,
    :grandmother => 2,
    :grandfather => 3
  }

In logic:

if u.type == User::TYPES[:mom]

Even though it's longer, I felt it to be more intuitive for other developers when they're reading my code. Thanks to Taro below for this solution.

Edit
Report

1 Answer

1

One way you be to write an file in initializers folder or lib folder

say app_contants.rb and in this file you can write

MOM=1

DAD=2
  1. Incase you write a initializer you can do

user.type == mom

2.If you create an lib file make it a module

 module app_constants
    mom = 1
    dad = 2
  end 

and simply include this module wherever you need

answered 2011-11-06T11:07:06.800

Your Answer