Alias for specific resourceful route's action ("/sign_in" instead of "/sessions/new")
I set up restful authentication and user management without any gems in Rails 3.
However, I think it's silly to need to go to "/sessions/new" instead of "/sign_in".
I know you can alias an entire resourc开发者_如何学编程e, so that instead of "/sessions"-and-friends my users could use "/squirrels"-and-friends, but that's not what I'm trying to accomplish here. I want to alias one specific action.
I know this can kind of be accomplished with
resources :sessions, :path_names => { :new => "sign_in" }
but then the route ends up as "/sessions/sign_in" — and I don't want the controller name in there at all for this action. I wish I could specify this with
resources :sessions, :path_names => { :new => "/sign_in" }
where the "/" tells rails that it is a complete path name. But that has the same effect as the first code fragment.
My last attempt was just to use the superficial
match "sign_in" => "sessions#new"
which allows someone to manually enter "/sign_in" in their URL bar, but links made with new_session_(path|url)
still land users at the more awkward "/sessions/sign_in".
match "sign_in" => "sessions#new", :as => :new_session
For newer versions of Rails you can no longer use match. Instead use the http verb.
Example:
get "sign_in" => "sessions#new", :as => :new_session
Note that i've used get
instead of match.
Tested on Rails 4.0.0
Add this line:
map.sign_in '/sign_in', :controller => 'session', :action => 'new'
To your config/routes.rb
.
The
match "sign_in" => "sessions#new"
line creates a route called "sign_in" which you can use in place of "new_session". So anywhere you had been linking to things with "new_session_path", replace it with "sign_in_path".
That's good enough. What I was originally hoping to do would be nice, though--to have "new_session_path" link to the same thing as "sign_in_path". To be able to specify a path_name that doesn't include the controller in it. Then I wouldn't need the match
line at all.
How about the "path" attribute? This should do what you want.
devise_for :users,
path: '',
controllers: {
sessions: "user/sessions",
passwords: "user/passwords",
confirmations: "user/confirmations",
registrations: "user/registrations"
},
path_names: {
sign_in: "login",
sign_out: "logout",
}
精彩评论