在Rails中设置静态路由

时间:2014-09-28 15:07:46

标签: ruby-on-rails ruby dynamic routes match

需要一些Rails帮助(使用rails 4.0.8和ruby 2.0.0)...

我试图重构我的路线,所以不要......

App::Application.routes.draw.do
   get "static_pages/home"
   get "static_pages/help"
   get "static_pages/about"
   get "static_pages/contact"
end

..在我的路线中,我将其设置为....

App::Application.routes.draw.do
   root 'static_pages#home'
   match '/help', to: 'static_pages#help', via: 'get'
   match '/about', to: 'static_pages#about', via: 'get'
   match '/contact', to: 'static_pages#contact', via: 'get'
end

...但是当我这样做时,我认为"匹配' / about' "应该自动创建命名路由,以便在控制器和视图中使用,看起来像......

about_path -> '/about'
about_url -> 'http://localhost:3000/about'

...但它在我的控制器中没有这样做。所以我想,"好的,我会手动将它们放入",所以我制作了app / controllers / static_pages_controller.rb ......

class StaticPagesController < ApplicationController
   def home
      root_path -> '/'
      root_url -> 'http://localhost:3000/'
   end

   def help
      help_path -> '/help'
      help_url -> 'http://localhost:3000/help'
   end

   def about
      about_path -> '/about'
      about_url -> 'http://localhost:3000/about'
   end

   def contact
      contact_path -> '/contact'
      contact_url -> 'http://localhost:3000/contact'
   end
end

......没有做任何事情。因此,现在当我尝试转到主页时,我收到路由错误没有路由匹配[GET]&#34; / static_pages / home&#34;

我是铁轨开发的新手,所以我确定我在这里找不到相当明显的东西。任何人都可以了解一下发生了什么?非常感谢。

编辑1与答案

BroiSatse和Ako给出了答案......

在路由配置中,我正在使用as:键,因此将我的代码更新为

App::Application.routes.draw.do
  root 'static_pages#home'
  match '/help', to: 'static_pages#help', via: 'get', as: :help
  match '/about', to: 'static_pages#about', via: 'get', as: :about
  match '/contact', to: 'static_pages#contact', via: 'get', as: :contact
end

诀窍。谢谢!

2 个答案:

答案 0 :(得分:4)

您丢失的所有内容都是as密钥:

App::Application.routes.draw.do
  root 'static_pages#home'
  match '/help', to: 'static_pages#help', via: 'get', as: :help
  match '/about', to: 'static_pages#about', via: 'get', as: :about
  match '/contact', to: 'static_pages#contact', via: 'get', as: :contact
end

添加密钥将使路由命名,并将创建所需的url_helpers。

编辑:

但是,你可以做得更好:

App::Application.routes.draw.do
  root 'static_pages#home'

  scope controller: :static_pages do
    get :help
    get :about
    get :contact
  end
end

答案 1 :(得分:0)

要定义命名路线,您可以执行以下操作:

match '/about', to: 'static_pages#about', via: 'get', as: :about

这将为您提供about_path

您可以找到有关命名路线here的更多信息。