ruby 注销链接的路由问题?DELETE vs GET操作?

vcirk6k6  于 2023-06-22  发布在  Ruby
关注(0)|答案(5)|浏览(189)

现在我的注销链接的路由指向sessions#destroy,但它不是HTTP删除动词,所以它不起作用。这个问题让我很沮丧,因为我应该能自己弄清楚,但到目前为止我还没有运气。以下是我在尝试注销时收到的错误消息:
没有与[DELETE]“/logout”匹配的路由
下面是我的routes文件:

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

sessions控制器中的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>

耙式路由相关结果:

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

谢谢你的帮助

iovurdzv

iovurdzv1#

您有两个选择:
1.更改链接以使用定义的路径

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

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

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

resource :sessions, only: [:new, :create, :destroy]

1.更改路线从

get 'logout' => 'sessions#destroy'

delete 'logout' => 'sessions#destroy'

在任何情况下,会话上的复数resources都没有意义。

b1uwtaje

b1uwtaje2#

match '/logout', to: 'session#destroy', via: 'delete'添加到routes.rb文件中
执行rake routes检查应用程序支持的路由。

oyxsuwqo

oyxsuwqo3#

在routes.rb文件中,将注销的 predicate 设置为get:

get 'logout' => 'sessions#destroy'

您需要将其设置为删除:

delete 'logout' => 'sessions#destroy'
s4chpxco

s4chpxco4#

从Rails 7(至少)开始,可以创建一个链接,在单击时使用DELETE方法执行请求。
将属性data-turbo-method='delete'添加到链接。
例如:

= link_to 'Logout', destroy_user_session_path, data: { turbo_method: :delete }
taor4pac

taor4pac5#

从Rails 7开始,您可能需要做类似的事情
<%= link_to "logout", destroy_user_session_path, data: { turbo_method: :delete" } %>

相关问题