On Tue, May 13, 2008 at 2:01 PM, Alex W.
[email protected] wrote:
I have a “page” model, and I want to be able access those pages with a
URL like: http://foo.com/my_page_name
- Use a low priority route that will match any single parameter URL.
This route will call the page controller and show the page. Since its
low priority, it only triggers if no other routes match. This seems
like it might make 404’s a bit messy to handle since I’m basically
creating a catch all that shouldn’t always work.
I do something a lot like this for my app. After the normal rails
default route, I catch everything else with my show_page route. My
page controllers show action checks the db for a page with the
appropriate path and displays it - or renders my custom “not found”
message with a status code of 404.
routes.rb
Install the default routes as the lowest priority.
map.connect ‘:controller/:action/:id’
map.connect ‘:controller/:action/:id.:format’
Finally let CMS figure out what to do with fall through pages
map.show_page ‘*url_parts’, :controller => “pages”, :action => “show”
pages_controller.rb
def show
@page = Page.find_by_url_parts(params[:url_parts])
respond_to do |format|
if @page
store_location
response.headers['Last-Modified'] =
@page.updated_at.to_s(:rfc822)
format.html # show the page
format.xml { render :xml => @page }
else
format.html {
title = “Page Not Found”
body = ‘
Please use the search box above
’
render_404( [“”], title, body)
}
format.xml { head :status => :not_found }
end
end
end
and in my application.rb controller, the render_404 method:
def render_404(base, title, body)
@page = Page.find_by_url_parts( base )
@page.body = body
@page.title = title
render :template => “pages/show”, :status => 404
end
render_404 grabbing a page (the home page) is so that the styling and
navigation stuff gets built and sent to the user.
–
Cynthia K.