2016-08-18 80 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,以便自定義的路線首先匹配。