0

I have a home controller which I am planing to use just for pages such as aboutus, contactus, or landing page etc. What is the best way to include this in the routes file that I do not get the default routes at all but do get to access each of the actions as a /[action] from the root of the site.

eg:

xyz.com/aboutus should take me to home#aboutus
xyz.com/contactus should take me to home#contactus

etc.

Qaiser Wali
  • 358
  • 5
  • 21

2 Answers2

5
#config/routes.rb
resources :home, path: "", only: [] do
   collection do
      get :aboutus
      get :contactus
   end
end

Loop removed by @Sanket

This will create domain.com/aboutus etc for all your pages

--

DRY

Although this is what you want, a much DRYer way to get it to work is to do the following:

#config/routes.rb
resources :home, path: "", only: :show #-> domain.com/:id

This means you can then use a gem such as friendly_id to create a series of slugs for your pages, like this:

#app/models/page.rb
class Page < ActiveRecord::Base
    extend FriendlyId
    friendly_id :title, use: [:slugged, :finders]

    #fields
    id | slug | title | body | created_at | updated_at
end

#app/controllers/home_controller.rb
def show
   @page = Page.find params[:id]
end

If you just want to render the pages without the model:

#app/controllers/home_controller.rb
def show
   render "pages##{params[:id]}"
end

This will allow you to use the likes of domain.com/home/aboutus in the most DRY way

--

Caveat

A big caveat to this is if you're going to be using app-wide slugs, you need to put them at the bottom of your routes.rb file (so they will not interfere with other routes)

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

You can just use https://github.com/thoughtbot/high_voltage a good gem for static pages.

BGuimberteau
  • 249
  • 1
  • 8