2010-04-29 63 views
2

我有几个常量是我不想创建数据库记录的数组,但我不知道在哪里存储常量而不会出现错误。哪里把常量在Rails中

例如

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

我在哪里可以存储此,因此所有的模型和控制器访问呢?

+3

见http://stackoverflow.com/questions/1107782的 – mckeed 2010-04-29 08:17:23

+0

可能重复http://stackoverflow.com/questions/1107782/wheres-the-best-place-to-define- a-constant-in-a-ruby-on-rails-application – 2010-04-29 08:21:33

回答

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]] } 
+0

但在最后几天,我找到了,模块方式更好 – 2010-04-29 09:38:19

2

我把它们直接放在模型类中。

class User < ActiveRecord::Base 
USER_STATUS_ACTIVE = "ACT" 
USER_TYPES = ["MANAGER","DEVELOPER"] 
end 
+0

这就是我所做的。 – 2010-04-29 08:48:16