2

I have a few constants which are arrays that I don't want to create databse records for but I don't know where to store the constants without getting errors.

For example

CONTAINER_SIZES = [["20 foot"],["40 foot"]]

Where can I store this so all models and controller have access to this?

John Topley
  • 113,588
  • 46
  • 195
  • 237
thenengah
  • 42,557
  • 33
  • 113
  • 157

2 Answers2

2

I put them directly in the model class.

class User < ActiveRecord::Base
USER_STATUS_ACTIVE = "ACT"
USER_TYPES = ["MANAGER","DEVELOPER"]
end
randika
  • 1,519
  • 3
  • 18
  • 39
2

I will write my way to you.

class User < ActiveRecord::Base   
  STATES = {
    :active => {:id => 100, :name => "active", :label => "Active User"},
    :passive => {:id => 110, :name => "passive", :label => "Passive User"},
    :deleted => {:id => 120, :name => "deleted", :label => "Deleted User"}
  }

  # and methods for calling states of user

  def self.find_state(value)
    if value.class == Fixnum
      Post::STATES.collect { |key, state|
        return state if state.inspect.index(value.to_s)
      }
    elsif value.class == Symbol
      Post::STATES[value]
    end
  end
end

so i can call it like

User.find_state(:active)[:id]

or

User.find_state(@user.state_id)[:label]

Also if i want to load all states to a select box and if i don't want some states in it (like deleted state)

def self.states(arg = nil)
  states = Post::STATES
  states.delete(:deleted)
  states.collect { |key, state|
    if arg.nil?
      state
    else
      state[arg]
    end
  }
end

And i can use it now like

select_tag 'state_id', User.states.collect { |s| [s[:label], s[:id]] }
Mehmet Davut
  • 667
  • 10
  • 30