Rick,
Good question. I think there are a lot of ways to get the job done here.
One method I’ve used in the past is to generate a “pages” controller (or
‘static’, or whatever you want to call it) and then create named routes
for my individual pages. So for your situation I would put this in my
routes file:
map.root :controller => ‘pages’, :action => ‘home’ (map.root creates the
route for ‘/’)
map.news ‘news’, :controller => ‘pages’, :action => ‘news’
map.links ‘links’, :controller => ‘pages’, :action => ‘links’
map.links ‘about-us’, :controller => ‘pages’, :action => ‘about_us’
The only thing you have to do is make sure you have a home.html.erb,
news.html.erb, and links.html.erb in the app/views/pages directory.
There are many other ways to solve this problem, and I would also be
curious to see what others recommend.
Josh S. recently blogged about this here
has_many :through - simple pages. That’s another way
of doing it, although I prefer using named routes generally because I
like having more control over the way my url looks (I can tell my URL to
say ‘about-us’ instead of ‘about_us’), but either way is completely
legit I think.
For a more advanced solution to this problem, also check out Ryan B.
Railscast on dynamically generating named routes. It’s more of an a cool
example of the dynamic nature of Ruby (generating a method at run-time
== very cool) but it may be what you’re looking for.
Hope all this helped and I’ll check back to see what other say in this
thread. I know there are a lot of ways to skin a cat here.
– Josh N. Abbott
P.S. Cool tip: Next time you’re in console and you’ve just added a named
route or resource to your routes.rb and you want to see if it works
simply type app.get ‘/about-us’ (or whatever your relative path would
look like. You’ll get back a status code telling you if it was found
(200) or not (404). You don’t even have to have the controller. It’ll
run straight off routes.rb.
Rick S. wrote:
If I have a site with pages “/home”, “/news”, “/links”, etc. I’m
trying to decide the best routing strategy. This is different than
the resource mapping used by the scaffold. For example, you would
never want to add a new home, or delete a home, etc.
I could have a “pages” controller with actions home, news, links.
Then I could add a route so that “/home” maps to “/pages/home”.
Or I could have separate controllers, and each controller only has an
index method. (A home controller, a news controller, etc.) In this
case, no routes are added to routes.rb.
This must be a common situation…what is the best way to handle it?