Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best place to store model specific constants in rails 3.1?

Tags:

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.

like image 485
Hopstream Avatar asked Nov 06 '11 10:11

Hopstream


2 Answers

Something like:

class User < ActiveRecord::Base    TYPES = %w{ mom dad grandmother grandfather son }    TYPES.each_with_index do |meth, index|     define_method("#{meth}?") { type == index }   end  end   u = User.new u.type = 4 u.mom? # => false u.son? # => true 
like image 65
taro Avatar answered Oct 20 '22 12:10

taro


Since Rails 4.1, there is support for ActiveRecord::Enum.

There's a useful tutorial here, but in short:

# models/user.rb class User < ActiveRecord::Base   enum family_role: [ :mum, :dad, :grandmother] end  # logic elsewhere u = User.first u.family_role = 'mum' u.mum? # => true u.family_role # => 'mum' 

Note: To convert from your current scheme (where your database already stores numbers corresponding to values), you should use the hash syntax:

enum family_role: { mum: 0, dad: 1, grandmother: 2 } 

I would additionally propose that you reserve 0 for the default state, but that's just one convention and not critical.

like image 21
Ollie Bennett Avatar answered Oct 20 '22 11:10

Ollie Bennett