Use plain YAML or JSON files to store static data

Ruby on Rails DB

When you have repeated pieces of text content that won’t change much over time, it may be a good idea to review your storing approach. If the content doesn't involve complex CRUD operations, having a dedicated table in your database can be overkill. There's another way!

A typical example of non-DB content storing strategy can be applied for « Frequently Asked Questions ». They are purely static : plain text, their format is invariable and they're not likely to evolve a lot. We can store them in straight them in a dedicated file and be done with it. Let’s see how :

  1. Create a YAML (my preference) or JSON file to store your FAQs in your project, for example in app/views/pages

    # faq.yaml
    - question: What is FAQ?
    answer: FAQ stands for Frequently Asked Questions.
    - question: What is YAML?
      answer: YAML stands for Yet Another Markup Language.
    // faq.json
        "question": "What is FAQ?",
        "answer": "FAQ stands for Frequently Asked Questions."
        "question": "What is YAML?",
        "answer": "YAML stands for Yet Another Markup Language."
  2. In the controller of your choice, load the YAML or JSON file

    class PagesController < ApplicationController
      def faq
        @faq = YAML.load_file(Rails.root.join("app/views/pages/faq.yml"))
        # or JSON.parse(Rails.root.join("app/views/pages/faq.json").read)

    @faq will now hold an array of hashes that looks like this :

    [{"question"=>"What is FAQ?", "answer"=>" FAQ stands for Frequently Asked Questions."},
    {"question"=>"What is YAML?", "answer"=>"YAML stands for Yet Another Markup Language."}]
  3. Configure routes in your config/routes.rb file to map the FAQ's url to the controller action

    # config/routes.rb
    get 'faq', to:'pages#faq'
  4. In the view that will show the FAQ, iterate over the retrieved information from the YAML or JSON file

    <!-- app/views/pages/faq.html.erb -->
    <h1>Frequently Asked Questions</h1>
      <% @faq.each do |faq| %>
          <strong><%= faq.question %></strong><br>
          <p><%= faq.answer %></p>
      <% end %>

Now, when you access the /faq route, you'll see a list of your FAQ without needing a database table!