Zando
Zando

Reputation: 5555

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:

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:

link_to customer.name, customers_payments_path(customer)

(customers_payments_path is not valid)

Upvotes: 0

Views: 250

Answers (3)

Ryan Bigg
Ryan Bigg

Reputation: 107738

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:

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.

Upvotes: 2

okeen
okeen

Reputation: 3996

You need to add the :as parameter to add a name to the route, so you can access it from a url_helper:

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

Then in your views/controllers/tests:

link_to "Confirm", show_confirmation_url(confirmation)

Upvotes: 0

Gazler
Gazler

Reputation: 84190

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

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

From the above link:

You can specify a name for any route using the :as option.

Upvotes: 3

Related Questions