如何简化这个routes.rb代码?

时间:2013-05-28 23:58:05

标签: ruby-on-rails ruby

这是我当前的路线.rb代码:

Mysite::Application.routes.draw do
  get "pages/home"

  get "pages/about"

  get "pages/resume"

  get "pages/contact"

  root :to => "pages#home"

  match "/about", to: "pages#about"
  match "/resume", to: "pages#resume"
  match "/contact", to: "pages#contact"
end

有没有办法简化我的根目录到页面控制器的路由?我可以将整个根目录与页面控制器本身匹配,而不是将根目录中的每一条路由与页面控制器操作相匹配吗?

4 个答案:

答案 0 :(得分:1)

删除前四个get。您的rootmatch声明可以正常使用。

Mysite::Application.routes.draw do

  match "/about", to: "pages#about"
  match "/resume", to: "pages#resume"
  match "/contact", to: "pages#contact"
  root :to => "pages#home"

end

答案 1 :(得分:0)

如果您想要“pages / about”之类的路径,那么

Mysite::Application.routes.draw do

  root :to => "pages#home"

  scope '/pages' do
    match "/about", to: "pages#about"
    match "/resume", to: "pages#resume"
    match "/contact", to: "pages#contact"
  end

end

答案 2 :(得分:0)

如果您确实想要将整个根目录路由到页面控制器,则可以绘制 cath all 路由:

  match '/*path', to: 'pages#show'

在您的路线结束时这样做会捕获所有不经常定义的请求。 在您的页面#show中,您可以检查路径并尝试查找匹配的页面 即。

  search =  params[:path].split('/').last

获取路径的最后一部分

  @page = Page.find_by_titel_or_id search

尝试按标题查找匹配的页面。 (由CMS如refinery_cms完成)

答案 3 :(得分:0)

Mysite::Application.routes.draw do
# Layout
  resources :pages do
    get 'about' => 'pages#about', :on => :collection
    get 'resume' => 'pages#resume', :on => :collection
    get 'contact' => 'pages#contact', :on => :collection
  end
  match 'About' => 'pages#about', :as => :About
  match 'Resume' => 'pages#resume', :as => :Resume
  match 'Contact' => 'pages#contact', :as => :Contact
  root :to => "pages#home"
end

现在您可以直接使用此匹配项,如

<a href='/Contact'>Contact Us</a>