Dynamically displaying pages in Rails

Rails is a great environment, but its conventions can sometimes cause you headaches. I’ve had one such headache for the last week or so now. I am trying load html content out of the database, based on the URI. In most environments this is easy. In rails it is easy too (ridiculously easy).

It is as simple as this:

a table:

the database table

routes.rb:

  1. ActionController::Routing::Routes.draw do |map|
  2. # Add your own custom routes here.
  3. # The priority is based upon order of creation: first created -> highest priority.
  4.  
  5. map.connect ‘:controller/:action/:id’
  6.  
  7. # default catch-all for URLs
  8. map.connect ‘:url’, :controller => ‘page’, :action => ‘view’, :requirements => { :url => /.*/ }
  9.  
  10. end

A model:

creating the Page model

And a controller:

Creating a page controller

  1. class PageController < ApplicationController
  2.  
  3. def view
  4. render :text => view_page(params[‘uri’]), :layout => true
  5. end
  6.  
  7. private
  8. def view_page(page_name = “”)
  9. @pages = Page.find_by_sql [“select * from pages where name=?”, page_name]
  10. if @pages.first
  11. @pages.first.html
  12. else
  13. “Could not find page ‘#{page_name}’”
  14. end
  15. end
  16. end