[英]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. 我正在努力解决路由在Rails中的工作原理。 Basically I'm attempting to create a simple CMS.
基本上,我正在尝试创建一个简单的CMS。
Users will be able to CRUD pages and therefore there has to be some sort of dynamic functionality somewhere. 用户将能够CRUD页面,因此某处必须具有某种动态功能。
I've created a simple Page model with ID, Name and Content. 我创建了一个具有ID,名称和内容的简单Page模型。
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). (我认为解决方案是将页面名称传递给相关的控制器和操作,测试它是否匹配数据库中的任何页面,以及是否显示页面内容)。
the canonical solution is to override to_param
in your model to return a unique, url-compatible page name : 规范的解决方案是在模型中重写
to_param
以返回唯一的,与url兼容的页面名称:
def to_param
title.parameterize
end
this way, all url helpers will use this value to build urls : 这样,所有url助手都会使用此值来构建url:
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]
). 然后在您的控制器中,您将必须以某种方式实现能够从其参数中获取页面的finder方法(该参数将在
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. 将此路线放置在
routes.rb
的末尾,否则它将捕获所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.