【问题标题】:Where to put constants in RailsRails 中常量的存放位置
【发布时间】:2010-04-29 08:15:14
【问题描述】:

我有一些常量是数组,我不想为其创建数据库记录,但我不知道在哪里存储常量而不会出错。

例如

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

我可以将它存储在哪里,以便所有模型和控制器都可以访问它?

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

我会写信给你。

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

【讨论】:

  • 但是前几天找了找,模块方式比较好
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2021-10-17
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多