我正在尝试设置我的routes.rb,以便在网址中登录和退出网站时不需要/ sessions /。以下是我的样本,以显示我想要实现的目标。虽然"第二次尝试"实际上做了我想做的事情,我想知道是否有更有效的方法。我对rails非常陌生,我确信routes.rb有一些选项可以做我在三条大行中所做的事情。
首次尝试
的routes.rb
namespace :account do
resources :users
resources :sessions
end
$ rake routes
Prefix Verb URI Pattern Controller#Action
account_users GET /account/users(.:format) account/users#index
...
account_sessions GET /account/sessions(.:format) account/sessions#index
POST /account/sessions(.:format) account/sessions#create
new_account_session GET /account/sessions/new(.:format) account/sessions#new
edit_account_session GET /account/sessions/:id/edit(.:format) account/sessions#edit
account_session GET /account/sessions/:id(.:format) account/sessions#show
PATCH /account/sessions/:id(.:format) account/sessions#update
PUT /account/sessions/:id(.:format) account/sessions#update
DELETE /account/sessions/:id(.:format) account/sessions#destroy
第二次尝试
的routes.rb
namespace :account do
resources :users
match '/login', :controller => 'sessions', :action => 'new', :via => [:get]
match '/login', :controller => 'sessions', :action => 'create', :via => [:post]
match '/logout', :controller => 'sessions', :action => 'destroy', :via => [:delete]
end
$ rake routes
Prefix Verb URI Pattern Controller#Action
account_users GET /account/users(.:format) account/users#index
...
account_login GET /account/login(.:format) account/sessions#new
POST /account/login(.:format) account/sessions#create
account_logout DELETE /account/logout(.:format) account/sessions#destroy
这可以在不必手动指定匹配位置的情况下完成吗?我想做的就是删除/ sessions /作为一项要求。
答案 0 :(得分:1)
我希望你在第二个例子中意识到你有/login
两次。这样可以简化它,但是您必须始终匹配要在任何默认值之外指定的每个路径。
namespace :account do
match '/login', to: 'sessions#new', via: [:get]
match '/logout', to: 'sessions#destroy', via: [:delete]
end
答案 1 :(得分:1)
namespace :account do
resources :users #-> account/users
resources :sessions, path: "", path_names: { new: "login", create: "login", destroy: "logout" } #-> accounts/login, accounts/logout
end
答案 2 :(得分:0)
在rails3中,我们应该按照以下方式使用with_options:
scope '/account' do
match '/login' => "sessions#new", :as => :login
post '/:login' => 'sessions#create', :as => :signup_create
delete '/:logout' => 'sessions#destroy', :as => :logout
end