Search code examples
ruby-on-rails-3postroutescustom-action

Creating Custom Post Method


I'm trying to create a a custom post method but i'm having trouble finding how to start.

What I want to do is to be able to read a CSV file, foreach entry, insert a new row into a database.

In the index file, I want to be able to hit 1 link or button to start a custom method.

This method would open my csv file (traverse each row and insert into database)

So essentially on my index.html.erb I would like to see something like:

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

I believe I need to edit my routes.rb and this is where I'm stuck. How do I make it so that my routes know that MyCustomAction is a post.

My Rake Route:

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

Thanks


Solution

  • You can try:

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

    This blog post may also help you if you want to do member instead of collection