2016-08-18 79 views
-2

这是我目前工作的routes.rb文件:资源如何在Rails中工作?

Rails.application.routes.draw do 

    get 'static_pages/help' 
    get 'static_pages/test', as: "can_do_this" 
    get 'static_pages/home', to: "static_pages#home", as: "home" 
    root 'application#hello' 

end 

但是,如果我添加一行:

Rails.application.routes.draw do 

    resources :static_pages #added this line 
    get 'static_pages/help' 
    get 'static_pages/test', as: "can_do_this" 
    get 'static_pages/home', to: "static_pages#home", as: "home" 
    root 'application#hello' 

end 

然后我的代码休息和我的网页上我有任何的内容不会显示。有人能向我解释这条线是什么以及如何使用它?

+2

请阅读文档http://guides.rubyonrails.org/routing.html –

回答

0

资源:static_pages将创建这些7条路线你

GET  /static_pages     static_pages#index 
GET  /static_pages/new    static_pages#new 
POST  /static_pages     static_pages#create 
GET  /static_pages/:id    static_pages#show 
GET  /static_pages/:id/edit   static_pages#edit 
PATCH/PUT /static_pages/:id    static_pages#update 
DELETE  /static_pages/:id    static_pages#destroy 

当你需要有控制器代表static_pages以及和所需的看法。

希望这有助于..

让我知道,如果你还有任何疑问..

0

添加这行代码在你routes.rb

resources :static_pages 

将产生以下宁静的路线

static_pages GET /static_pages(.:format)   static_pages#index 
       POST /static_pages(.:format)   static_pages#create 
new_static_page GET /static_pages/new(.:format)  static_pages#new 
edit_static_page GET /static_pages/:id/edit(.:format) static_pages#edit 
    static_page GET /static_pages/:id(.:format)  static_pages#show 
       PATCH /static_pages/:id(.:format)  static_pages#update 
       PUT /static_pages/:id(.:format)  static_pages#update 
       DELETE /static_pages/:id(.:format)  static_pages#destroy 
0

正如其他答案中提到的,resources :static_pages创建了几条路线。其中有这样一句:

static_page GET /static_pages/:id(.:format)  static_pages#show 

所以,当你提出要求,例如,http://localhost:3000/static_pages/help,它是这条路线,这个URL匹配。它使用参数{'id' => "help"}调用StaticPagesController#show动作。您的自定义help操作未被考虑,因为已找到匹配路线。

一对夫妇在这里可能的方式:

  1. show动作(通过ID)服务您的静态页面和删除自定义路线。
  2. 将您的自定义路线后的地方resources :static_pages,以便自定义的路线首先匹配。