Reputation: 6027
I am trying to make a stupid simple CMS for one of my clients using rails. I generated scaffolding for Page
and have been successful at creating and rendering those pages, however, the routing is ugly.
Right now, if I want to view the home page, I get a url like this: example.com/pages/1
I'd like to accomplish 2 things:
How do I set the routing so that example.com
automagically grabs the page named "home"
and
How do I set the routing so that example.com/page/page_name
performs a
@page = Page.find_by name: 'page_name'
Upvotes: 0
Views: 73
Reputation: 9025
Here's a solution that assumes your controller is named pages_controller
instead of page_controller
.
Add these routes in config/routes.rb
:
root to: 'pages#show', page_name: 'home'
get 'pages/:page_name', to: 'pages#show'
For the controller app/controllers/pages_controller.rb
:
class PagesController < ApplicationController
def show
@page = Page.find_by(name: params[:page_name])
end
end
Note: In rails4 the find_by
dynamic finders have been deprecated... so if you're app is on 4 you should look into updating them. These docs have further details.
Also, if you're just trying to get static looking urls then I would definitely go with Marian Theisen's suggestion and use friendly_id.
Upvotes: 1
Reputation: 529
To accomplish the first thing you need to open the file routes.rb which is in the config folder and add the following:
root to: "home#index"
I'm assuming you have a controller named home which contains a method called index and this is the one that displays the home page. If you want to make it the same as example.com/pages then you would have to use
root to: "pages#index"
to make a general rule you need to use
root to: "controller#method"
Don't forget to remove the index.html from the public folder too. I recommend you make the blog application presented here: http://guides.rubyonrails.org/getting_started.html It can help you understand more.
Upvotes: 1
Reputation: 10997
Q1:
How do I set the routing so that example.com automagically grabs the page named "home"
In `routes.rb:
root :to => '[controller]#[action]'
#'pages#home' for example, if your home page is in `pages_controller`
# and uses the `home` action
Q2:
How do I set the routing so that example.com/page/page_name performs a
@page = Page.find_by name: 'page_name'
match '/page/:name', :to => 'pages#some_name', :as => :some_name
this would generate the following in $rake routes
:
some_name /page/:name(.:format) pages#some_name
when you link to (or redirect, or otherwise access) this page, you'd write
link_to "click this link!", some_name_path(@SomeModel.some_name)
Upvotes: 1