Where to put constants in Rails
I have a few constants that are arrays that I don't want to create database records, but I don't know where to store the constants without getting errors.
for instance
CONTAINER_SIZES = [["20 foot"],["40 foot"]]
Where can I save this so that all models and controller can access this?
+2
a source to share
2 answers
I'll 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 in the select box, and if I don't want some states in it (like a 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]] }
+2
a source to share