How to add custom routes to resource route

Sathish Manohar picture Sathish Manohar · May 22, 2013 · Viewed 27.2k times · Source

I have an invoices_controller which has resource routes. Like following:

resources :invoices do
  resources :items, only: [:create, :destroy, :update]
end

Now I want to add a send functionality to the invoice, How do I add a custom route as invoices/:id/send that dispatch the request to say invoices#send_invoice and how should I link to it in the views.

What is the conventional rails way to do it. Thanks.

Answer

Damien picture Damien · May 22, 2013

Add this in your routes:

resources :invoices do
  post :send, on: :member
end

Or

resources :invoices do
  member do
    post :send
  end
end

Then in your views:

<%= button_to "Send Invoice", send_invoice_path(@invoice) %>

Or

<%= link_to "Send Invoice", send_invoice_path(@invoice), method: :post %>

Of course, you are not tied to the POST method