Reputation: 10077
I'm trying to wrap my head around how routing works in rails. Basically I'm attempting to create a simple CMS.
Users will be able to CRUD pages and therefore there has to be some sort of dynamic functionality somewhere.
I've created a simple Page model with ID, Name and Content.
The urls would match to each page name would be to display the Content of each page:
How do I match the url to the correct page?
(I think the solution is to the pass the page name to the relevant controller and action, test if it matches any pages in the database and if it does display the page content).
Upvotes: 0
Views: 67
Reputation: 12554
the canonical solution is to override to_param
in your model to return a unique, url-compatible page name :
def to_param
title.parameterize
end
this way, all url helpers will use this value to build urls :
page_path(@some_page) # => 'pages/some-page-title'
then in your controller, you will somehow have to implement a finder method able to fetch a page from its param (the param will be available in params[:id]
). It usually goes like this :
class Page < ActiveRecord::Base
def self.from_param(param)
where(title: param).first
end
def self.from_param!(param)
from_param(param) || fail(ActiveRecord::RecordNotFound)
end
end
Now, if you want your pages to be accessible from the root path, you can do :
Rails.application.routes.draw do
resources :pages, path: '/'
end
Beware ! place this route at the end of routes.rb
, or it will catch everything.
Upvotes: 1