Search code examples
ruby-on-railsruby-on-rails-3rails-routing

How to add custom routes to resource route


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.


Solution

  • 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