Named route for non resource nesting

2019-08-10 06:56发布

问题:

I'm trying to generate a link for a user to click to confirm their account. I'm wanting this:

/users/:id/confirm/:code

I've got this in my routes file:

resources :users do
  member do
    get 'confirm/:confirmation_code', :action => 'confirm'
  end
end

I've tried:

user_confirm_path(@user, @confirmation_code)
confirm_user_path(@confirmation_code, @user)

and many others but can't seem to get the right one. I guess I could always generate the link url myself but that doesn't seem the rails way.

This is what my rake routes outputs:

rake routes
Prefix Verb   URI Pattern                                     Controller#Action
       GET    /users/:id/confirm/:confirmation_code(.:format) users#confirm

but omits the thing I'm actually looking for

回答1:

I'm not gonna give the solution right away, but I will give you the keys to solve the problem yourself: ("Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime.")

You can run the following command to list all the available routes in your app and the corresponding helpers:

rake routes

In my app, there is so many routes I can't see them all at once. So I add a | grep something to only select the part that I need. In your case, it would be something like:

rake routes | grep confirm

And you will probably end up reading an output like:

confirm_user_path GET /users/:id/confirm/:confirmation_code

Googling "rails 4.0.2 url helper", first link is a Github issue: https://github.com/rails/rails/issues/12751



回答2:

I had another similar question which was answered over here: Named routes inserting a . instead of a /

Using that same answer for this problem solved it.