perseverance
perseverance

Reputation: 6612

Where should I store a static list like states or cities in Ruby on Rails?

I want to prevent going to the database if possible. This is a rarely changing list of cities and states that will be populated in the beginning of the project and used by the application to format and find verify those locations.

So far from my research:

Kind of confused so want the best method for performance and convention.

Upvotes: 2

Views: 763

Answers (1)

Stephan
Stephan

Reputation: 2873

I would suggest going one of two ways:

  • create a ruby object by hand, which contains the data and can answer the relevant questions:

    class Cities
      def self.data
        {
          1: 'New York',
          2: 'Boston'
        }
      end
    
      def self.find_name_by_id(id)
        data[id]
      end
    end
    

    This means doing a bit more by hand and not having everything "free" that ActiveRecord normally gives you. Or...

  • If you are certain that you need all the bells and whistles of ActiveRecord you can also use a gem for this: https://github.com/zilkey/active_hash. It does what you want and can store the data to an object in a hash or a yaml file. It will do associations and offers the object methods that one is used to from ActiveRecord.

Upvotes: 2

Related Questions