路由到子文件夹

时间:2015-10-11 11:07:16

标签: ruby-on-rails

拥有一个使用静态页面控制器的Rails应用程序的帮助系统。

def show
  if valid_page?
   render template: "help/#{params[:page]}" 
else
  render file: "public/404.html", status: :not_found
end

有路线       得到帮助:页面' => ' help#show',:via => [:获得]

“帮助”文件夹开始变得压倒性地应用程序的所有静态视图。 所以我想将视图拆分为带有相关控制器的子文件夹 - 所以在Help文件夹中现在是

---Welcome
    ----index.html.erb
    ----about.html.erb
    ----contact.html.erb
---Blog 
    ----index.html.erb

在帮助文件夹下有二十几个子文件夹,每个子文件夹有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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下是它应该如何运作:

#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文件。虽然在某些情况下这是可以的,但在这种情况下,它会很快变得非常混乱。

您可以更好地创建Modeltable来存储您需要的help页面,以便进行整理和排序。根据需要调用它们。这样做的另一个好处是没有验证(Rails将处理所有这些),并且您将能够使用一个视图文件来使其正常工作:

#app/views/help/show.html.erb
<%= @page.title %>
<%= @page.body %>
相关问题