简体   繁体   English

对于Rails 3.x中的任意路由,如何使用UrlHelper访问它们?

[英]For arbitrary routes in Rails 3.x, how can I use UrlHelper to access them?

So I have a route in routes.rb like this: 所以我在routes.rb中有一条这样的路线:

get "customers/:id/payments", :controller=>"customers", :action=>"payments"

What would be the UrlHelper that would generate this, if any, when doing this in a view: 在视图中执行此操作时,将生成UrlHelper(如果有)的是什么:

link_to customer.name, customers_payments_path(customer)

(customers_payments_path is not valid) (customers_payments_path无效)

get "customers/:id/payments", :controller=>"customers", :action=>"payments", :as => 'customer_payments'

http://guides.rubyonrails.org/routing.html#naming-routes http://guides.rubyonrails.org/routing.html#naming-routes

From the above link: 从上面的链接:

You can specify a name for any route using the :as option. 您可以使用:as选项为任何路由指定名称。

I like Gazler's answer if it's only a one-off route, but if you've already got resource routes for customers then I would define this route like this: 如果只是一条一次性路线,我会喜欢Gazler的答案,但是如果您已经有客户的资源路线,那么我可以这样定义路线:

resources :customers do
  member do
    get :payments
  end
end

This way, you would still have the standard customers_path and customer_path helpers you'd normally get from a resource route, but it would also generate customer_payments_path in a shorter syntax. 这样,您仍将拥有通常从资源路由获得的标准customers_pathcustomer_path帮助程序,但也会以较短的语法生成customer_payments_path

You need to add the :as parameter to add a name to the route, so you can access it from a url_helper: 您需要添加:as参数来为路由添加名称,以便您可以从url_helper访问它:

get "confirmations/:code" => "confirmations#show", :as => "show_confirmation"

Then in your views/controllers/tests: 然后在您的视图/控制器/测试中:

link_to "Confirm", show_confirmation_url(confirmation)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM