How to add a custom action to the controller in Rails 3

ruby-on-rails

Solution

A nicer way to write

resources :items, :collection => {:schedule => :post, :save_scheduling => :put}

is

resources :items do
  collection do
    post :schedule
    put :save_scheduling
  end
end

This is going to create URLs like

- `/items/schedule`

- `/items/save_scheduling`

Because you're passing an `item` into your `schedule_...` route method, you likely want `member` routes instead of `collection` routes.

resources :items do
  member do
    post :schedule
    put :save_scheduling
  end
end

This is going to create URLs like

- `/items/:id/schedule`

- `/items/:id/save_scheduling`

Now a route method `schedule_item_path` accepting an `Item` instance will be available. The final issue is, your `link_to` as it stands is going to generate a `GET` request, not a `POST` request as your route requires. You need to specify this as a `:method` option.

link_to("Title here", schedule_item_path(item), method: :post, ...)

Recommended Reading: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Problem

I want to add another action to my controller, and I can't figure out how. I found this on RailsCasts, and on most StackOverflow topics: ``` # routes.rb resources :items, :collection => {:schedule => :post, :save_scheduling => :put} # items_controller.rb ... def schedule end def save_scheduling end # items index view: <%= link_to 'Schedule', schedule_item_path(item) %> ``` But it gives me the error: ``` undefined method `schedule_item_path' for #<#<Class:0x6287b50>:0x62730c0> ``` Not sure where I should go from here.

Original source