Ruby-on-rails 如何将自定义路由添加到资源路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16693185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:01:35  来源:igfitidea点击:

How to add custom routes to resource route

ruby-on-railsruby-on-rails-3rails-routing

提问by Sathish Manohar

I have an invoices_controllerwhich has resource routes. Like following:

我有一个invoices_controller有资源路线的。像下面这样:

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/sendthat dispatch the request to say invoices#send_invoiceand how should I link to it in the views.

现在,我想向发票添加发送功能,如何添加自定义路由以invoices/:id/send发送请求,invoices#send_invoice以及如何在视图中链接到它。

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

什么是传统的导轨方式来做到这一点。谢谢。

回答by Damien

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

当然,您并没有绑定到 POST 方法

回答by Arjan

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 sendaction of your invoices_controller.

它将转到send您的invoices_controller.

回答by Salil

match '/invoices/:id/send' => 'invoices#send_invoice', :as => :some_name

To add link

添加链接

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

回答by W.M.

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

在 Rails >= 4 中,您可以通过以下方式实现:

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

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