开发者

Where to put constants in Rails

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 = [[开发者_如何学Go"20 foot"],["40 foot"]]

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


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


I put them directly in the model class.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜