46

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.

Sathish Manohar
  • 5,859
  • 10
  • 37
  • 47

5 Answers5

51

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

Damien
  • 26,933
  • 7
  • 39
  • 40
  • Thanks! There was one problem though, when I use send method in controller, I get an argument error like this `ArgumentError in InvoicesController#show wrong number of arguments (2 for 0)` I guess rails uses the send keyword for some internals. Funny, changing all "send" to "bend" actually sent the emails, Now I guess, I have to figure out a new verb for sending invoices. – Sathish Manohar May 22 '13 at 14:20
  • @SathishManohar ah ah! I didn't think about that! Yes, `send` is a method in Ruby http://ruby-doc.org/core-2.0/Object.html#method-i-send. Maybe use `deliver` instead of `send` (my 2 cents) – Damien May 22 '13 at 14:44
4
resources :invoices do
  resources :items, only: [:create, :destroy, :update]
  get 'send', on: :member
end

<%= link_to 'Send', send_invoice_path(@invoice) %>

It will go to the send action of your invoices_controller.

Arjan
  • 6,264
  • 2
  • 26
  • 42
1
match '/invoices/:id/send' => 'invoices#send_invoice', :as => :some_name

To add link

<%= button_to "Send Invoice", some_name_path(@invoice) %>
Salil
  • 46,566
  • 21
  • 122
  • 156
1

In Rails >= 4, you can accomplish that with:

match 'gallery_:id' => 'gallery#show', :via => [:get], :as => 'gallery_show'

W.M.
  • 589
  • 1
  • 6
  • 13
0

resources :invoices do get 'send', on: :member end

Ruan Nawe
  • 363
  • 6
  • 9