我有一些常量,这些数组是我不想创建数据库记录但我不知道在哪里存储常量而不会出错。
例如
CONTAINER_SIZES = [["20 foot"],["40 foot"]]
我可以在哪里存储,以便所有模型和控制器都可以访问它?
答案 0 :(得分:2)
我把它们直接放在模型类中。
class User < ActiveRecord::Base
USER_STATUS_ACTIVE = "ACT"
USER_TYPES = ["MANAGER","DEVELOPER"]
end
答案 1 :(得分:2)
我会写信给你。
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
所以我可以称之为
User.find_state(:active)[:id]
或
User.find_state(@user.state_id)[:label]
此外,如果我想将所有状态加载到选择框,如果我不想要其中的某些状态(如删除状态)
def self.states(arg = nil)
states = Post::STATES
states.delete(:deleted)
states.collect { |key, state|
if arg.nil?
state
else
state[arg]
end
}
end
我现在可以像
一样使用它select_tag 'state_id', User.states.collect { |s| [s[:label], s[:id]] }