40

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,015
  • 8
  • 31
  • 44

5 Answers5

44

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
  • 23,941
  • 7
  • 36
  • 39
  • 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
3
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,089
  • 2
  • 23
  • 42
1
match '/invoices/:id/send' => 'invoices#send_invoice', :as => :some_name

To add link

<%= button_to "Send Invoice", some_name_path(@invoice) %>
Salil
  • 43,381
  • 19
  • 113
  • 148
1

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

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

W.M.
  • 292
  • 1
  • 3
  • 11
0

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

Ruan Nawe
  • 376
  • 4
  • 6