注销链接的路由故障? DELETE vs GET动作?

时间:2014-09-24 13:42:54

标签: ruby-on-rails ruby ruby-on-rails-4

现在我的注销链接的路由指向会话#dump,但它不是HTTP删除动词,所以它不起作用。这个问题令我感到沮丧,因为我应该能够自己解决这个问题,但到目前为止我还没有运气。以下是我在尝试注销时收到的错误消息:

没有路线匹配[DELETE]“/ logout”

这是我的路线档案:

Rails.application.routes.draw do



  get 'line_items/create'



  root 'static_pages#home'
  get 'testimonials' => 'static_pages#testimonials'
  get 'help' => 'static_pages#help'
  get 'about' => 'static_pages#about'
  get 'contact' => 'static_pages#contact'
  get 'signup' => 'users#new'
  get 'login' => 'sessions#new'
  get 'logout' => 'sessions#destroy'
  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  resources :products
  resources :categories
  resources :line_items
  resources :carts
 end

会话控制器中的destroy方法:

def destroy
  forget(current_user)
  session.delete(:user_id)
  @current_user = nil
  redirect_to root_url
end

退出链接:

          <li>
            <%= link_to "Log out", logout_path, method: "delete" %>
          </li>

rake路线的相关结果:

logout_path     GET     /logout(.:format)   sessions#destroy
users_path  GET     /users(.:format)    users#index
POST    /users(.:format)    users#create
new_user_path   GET     /users/new(.:format)    users#new
edit_user_path  GET     /users/:id/edit(.:format)   users#edit
user_path   GET     /users/:id(.:format)    users#show
PATCH   /users/:id(.:format)    users#update
PUT     /users/:id(.:format)    users#update
DELETE  /users/:id(.:format)    users#destroy
sessions_path   POST    /sessions(.:format)     sessions#create
new_session_path    GET     /sessions/new(.:format)     sessions#new
session_path    DELETE  /sessions/:id(.:format)     sessions#destroy 

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您有两种选择:

  1. 更改链接以使用已定义的路线

    <%= link_to "Log out", logout_path %>
    

    <%= link_to "Log out", session_path, method: "delete" %>
    

    请注意,为了使最后一个链接起作用,您需要将其更改为单一资源(资源,而不是资源)。

    resource :sessions, only: [:new, :create, :destroy]
    
  2. 更改路线
    get 'logout' => 'sessions#destroy'
    

    delete 'logout' => 'sessions#destroy'
    
  3. 在任何情况下,会话中的复数resources都没有意义。

答案 1 :(得分:0)

match '/logout', to: 'session#destroy', via: 'delete'添加到routes.rb文件

执行rake routes以检查应用程序支持的路由。

答案 2 :(得分:0)

在routes.rb文件中,您要将logout的动词设置为:

get 'logout' => 'sessions#destroy'

您需要将其设置为删除:

delete 'logout' => 'sessions#destroy'