How to add custom routes to resource route
29,037
Solution 1
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
Solution 2
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
.
Solution 3
In Rails >= 4, you can accomplish that with:
match 'gallery_:id' => 'gallery#show', :via => [:get], :as => 'gallery_show'
Solution 4
match '/invoices/:id/send' => 'invoices#send_invoice', :as => :some_name
To add link
<%= button_to "Send Invoice", some_name_path(@invoice) %>
Author by
Sathish Manohar
Self Taught. Web Designer, Developer. Building Cool Stuff that I want in this world.
Updated on July 09, 2022Comments
-
Sathish Manohar almost 2 years
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 sayinvoices#send_invoice
and how should I link to it in the views.What is the conventional rails way to do it. Thanks.
-
Sathish Manohar about 11 yearsThanks! 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. -
Damien about 11 years@SathishManohar ah ah! I didn't think about that! Yes,
send
is a method in Ruby ruby-doc.org/core-2.0/Object.html#method-i-send. Maybe usedeliver
instead ofsend
(my 2 cents)