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 :
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." } ]
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) end end
@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."}]
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'
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> <ul> <% @faq.each do |faq| %> <li> <strong><%= faq.question %></strong><br> <p><%= faq.answer %></p> </li> <% end %> </ul>
Now, when you access the /faq
route, you'll see a list of your FAQ without needing a database table!