需要一些 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
..在我的 route ,我将其设置为...
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
...但是当我这样做时,我认为“match '/about'”应该自动创建命名路由以在 Controller 和 View 中使用,看起来像...
about_path -> '/about'
about_url -> 'http://localhost:3000/about'
...但它在我的 Controller 中没有这样做。所以我想,“好吧,我会手动把它们放进去”,所以我制作了 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]“/static_pages/home”。
我是 Rails 开发的新手,所以我确信我在这里遗漏了一些相当明显的东西。任何人都可以阐明正在发生的事情吗?非常感谢。
编辑 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
成功了。谢谢!
最佳答案
您所缺少的只是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
关于ruby-on-rails - 在 Rails 中设置静态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086268/