Static pages in Ruby on Rails

后端 未结 9 1070
终归单人心
终归单人心 2020-12-04 05:47

What are the standard way of making a Ruby on Rails application that will have pages such as

  • Home
  • About
  • Contact

I would appric

9条回答
  •  自闭症患者
    2020-12-04 06:01

    Depends on how you want to handle the content in those pages.

    Approach #1 - store content in views

    If you just want to put all your content in ERB views, then a very simple approach is to create a PagesController whose purpose is to deal with static pages. Each page is represented by one action in the controller.

    pages_controller.rb:

    class PagesController < ApplicationController
      def home
      end
    
      def about
      end
    
      def contact
      end
    end
    

    routes.rb:

    match '/home' => 'pages#home'
    match '/about' => 'pages#about'
    match '/contact' => 'pages#contact'
    

    Then create home.html.erb, about.html.erb, and contact.html.erb views under app/views/pages. These views contain whatever content you want on your static pages. They'll by default use your app's application.html.erb layout.

    You'll also want to look into page caching to give yourself a boost in performance.


    Approach #2 - store content in database

    Another approach I've used is to make a very basic CMS for static pages. In this case, pages are represented in the model. It uses the friendly_id gem to handle slugs for each page so that they can be retrieved by a pretty name in the URL (e.g., /about) rather than by ID.

    page.rb:

    class Page < ActiveRecord::Base
      attr_accessible :title, :content
    
      validates_presence_of :title, :content
    
      has_friendly_id :title, :use_slug => true, :approximate_ascii => true
    end
    

    pages_controller.rb:

    class PagesController < ApplicationController
      def show
        @page = Page.find(params[:id])
        render 'shared/404', :status => 404 if @page.nil?
      end
    end
    

    show.html.erb:

    <%= raw @page.content %>
    

    routes.rb:

    match '/:id' => 'pages#show'
    

    Note: put this entry at the end of routes.rb since it matches everything.

    Then how you want to create, edit and update pages are up to you - you can have an admin interface, or build it in to your public interface somehow. This approach can benefit from page caching too.

提交回复
热议问题