有一个Rails应用程序的帮助系统,它使用静态页面控制器。
def show
if valid_page?
render template: "help/#{params[:page]}"
else
render file: "public/404.html", status: :not_found
end使用路由获取‘帮助:页’=> 'help#show',:via => :get
在应用程序的所有静态视图中,“帮助”文件夹开始变得压倒一切。因此,我想将视图拆分为带有关联控制器的子文件夹,因此在“帮助”文件夹中现在是。
---Welcome
----index.html.erb
----about.html.erb
----contact.html.erb
---Blog
----index.html.erb等
在“帮助”文件夹下有大约20多个子文件夹,每个子文件夹都有3-6个帮助文件,但没有为每个子文件夹创建路由,是否有一种方法可以有一个智能路径来引用控制器(文件夹)和页面。
get 'help:folder:page' => 'help#show', :via => [:get]
def show
if valid_page?
render template: "help/#{params[:folder]}/#{params[:page]}/"
else
render file: "public/404.html", status: :not_found
end有什么想法吗?
发布于 2015-10-12 12:06:54
下面是它的工作原理:
#config/routes.rb
resources :help, only: [:index, :show] #-> url.com/help/:id这将允许您使用以下内容:
#app/controllers/help_controller.rb
class HelpController < ApplicationController
def show
@page = Help.find params[:id]
#no need to rescue this, rails will automatically throw a 404 error if not found
end
end
#app/models/page.rb
class Page < ActiveRecord::Base
#columns id | type | title | body | created_at | updated_at
end
#app/models/help.rb
class Help < Page
end您的主要问题是将每个页面存储为一个.html.erb文件。虽然在某些情况下,这是可以的,但在这种情况下,它会变得非常混乱,很快。
您将更好地创建一个Model和table来存储所需的help页面,允许您根据需要对它们进行整理和调用。这样做的另一个好处是没有验证(Rails将处理所有这些),您将能够使用一个视图文件来使其工作:
#app/views/help/show.html.erb
<%= @page.title %>
<%= @page.body %>https://stackoverflow.com/questions/33064253
复制相似问题