2012-03-08 89 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