Named route for non resource nesting

旧巷老猫 提交于 2019-12-11 08:24:02

问题


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.



来源:https://stackoverflow.com/questions/21940065/named-route-for-non-resource-nesting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!