2012-03-08 82 views
2

我試圖創建一個自定義的POST方法,但我無法找到如何下手。創建自定義POST方法

我想要做的是能夠讀取CSV文件,foreach條目,並將新行插入數據庫。

在索引文件中,我希望能夠點擊1個鏈接或按鈕來啓動自定義方法。

此方法將打開我的csv文件(遍歷每一行,並插入到數據庫)

所以基本上我index.html.erb我想看到的東西,如:

<%= link_to "Load CSV to Database", :controller => MyController, :action => MyCustomAction %> 

我相信我需要編輯我的routes.rb,這是我卡住的地方。我如何做到這一點,以便我的路線知道MyCustomAction是一篇文章。

我耙路線:

use_database_csv_files POST /csv_files/use_database(.:format) csv_files#use_database 
     csv_files GET /csv_files(.:format)    csv_files#index 
        POST /csv_files(.:format)    csv_files#create 
     new_csv_file GET /csv_files/new(.:format)   csv_files#new 
    edit_csv_file GET /csv_files/:id/edit(.:format)  csv_files#edit 
      csv_file GET /csv_files/:id(.:format)   csv_files#show 
        PUT /csv_files/:id(.:format)   csv_files#update 
        DELETE /csv_files/:id(.:format)   csv_files#destroy 

感謝

回答

1

你可以試試:

resources :MyController do 
    collection do 
    post 'MyCustomAction' 
    end 
end 

blog post也可以幫助你,如果你想要做member代替collection

+0

謝謝斯科特。我已經添加了收藏集,但現在當我點擊鏈接時,它認爲MyCustomAction是和用於展示的ID。有沒有另一種方法我想生成link_to? – Pharsake 2012-03-09 16:59:40

+0

您可以嘗試'_path'路由。 「耙路線」將顯示路徑,例如, 'MyContoller_Action',你只需追加'_path'。 – ScottJShea 2012-03-09 17:28:26

+0

它仍然說同樣的事情,但它仍然假設我試圖訪問一個顯示方法,其中MyCustomAction是ID。我感謝你的幫助斯科特! – Pharsake 2012-03-09 18:12:45