简体   繁体   中英

How do I use a page id/name to load the correct controller action? (Ruby on Rails 4)

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:

  • example.com
  • example.com/about
  • example.com/news
  • example.com/staff

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM