2015-04-20 56 views
1

自定義操作export_file在routes.rb中定義:Rails - 動作和http動詞必須匹配嗎?

resource :payment_requests do 
     collection do 
     get :export_file 
     end 
    end 

form_tag,我們可以使用method: put爲export_file即使export_fileget

<%= form_tag export_file_payment_requests_path(format: 'csv'), method: :put do %> 
    ...... 
    <%= submit_tag 'CSV' %> 
<% end %> 

看來OK根據HTTP文件使用put方法get行動。

回答

1

本質上,沒關係 - 您絕對可以從Rails中的窗體發送PUT請求。

但是,如果您在routes.rb文件中指定一條路由爲get請求,它將只會使用HTTP GET動詞匹配它。

看看輸出從rake routes

   Prefix Verb  URI Pattern                 Controller#Action 
api_v1_search_simple GET  /api/v1/search/simple(.:format)            api/v1/search#simple 
    new_user_session GET  /auth/login(.:format)              devise/sessions#new 
     user_session POST  /auth/login(.:format)              devise/sessions#create 
destroy_user_session DELETE /auth/logout(.:format)              devise/sessions#destroy 
     user_password POST  /auth/password(.:format)              devise/passwords#create 
    new_user_password GET  /auth/password/new(.:format)             devise/passwords#new 
    edit_user_password GET  /auth/password/edit(.:format)            devise/passwords#edit 
         PATCH /auth/password(.:format)              devise/passwords#update 
         PUT  /auth/password(.:format)              devise/passwords#update 
    user_confirmation POST  /auth/confirmation(.:format)             devise/confirmations#create 
new_user_confirmation GET  /auth/confirmation/new(.:format)            devise/confirmations#new 
         GET  /auth/confirmation(.:format)             devise/confirmations#show 
       root GET /                   dashboards#show 

你看看它是如何列出Verb將對陣?

如果你想發送PUT請求,並有軌匹配一個特定的控制器和行動,那麼你應該將它指定你routes.rb文件put請求。

您可以選擇使用match通配符來定義路由,但通常認爲這是一件糟糕的事情,因爲它會打開您的應用程序以供濫用。

本指南是非常有用的:http://guides.rubyonrails.org/routing.html

如果你讀section 3.7,你會看到,你可以使用關鍵字matchvia屬性限制哪些動詞路線應該對陣一起。像這樣的:

match 'photos', to: 'photos#show', via: [:get, :post] 

你可以使用路由這樣的匹配對陣雙方GETPUT如果你需要它。

+0

感謝您的回答! '但是,如果你在你的routes.rb文件中指定了一個路由作爲get請求,它將只使用HTTP GET動詞匹配它。「 - 這是否意味着該動作(在routes.rb中聲明爲」get「 )將始終用http GET完成,無論在'method:'中如何? – user938363

+0

如果routes.rb和method中的操作不匹配,則rails路由將無法正確完成。這是我們在測試中發現的。所以在實際中,它們應該匹配。 – user938363

+0

我認爲你有點混淆事情。控制器中的「操作」可以有你喜歡的任何名稱。你的情況是'export_file'。由於您使用'get'關鍵字定義了該路線,因此如果請求是「GET」請求,則Rails將僅匹配它。 – Jon