code prodigy
code prodigy

Reputation: 77

session#destroy not being applied

I want to start this by saying i am not using devise. My problem is that i am making the authentication part of my website and I am running into a routing error.

I have tried many stack overflow solutions that have just not seemed to work for me.

This is my new.html.erb page where i am trying to destroy a user:

<h1> Hey, <%= @user.firstname %>! </h1>
<h3><a href="http://localhost:3000">Home</a></h3>
<%= link_to "Log Out", session_path, method: :delete %>
<%= stylesheet_link_tag 'users', media: 'all', 'data-turbolinks-track' => true %>

This is my routes.rb file:

Rails.application.routes.draw do
  # Fubyonrails.org/routing.html
  root :to => 'static#welcome'
  resources :users, only: [:new, :create, :show]
  resources :sessions, only: [:new, :create, :destroy]
  resources :studios
end

This is my session_controller.rb file:

class SessionsController < ApplicationController
  def new; end

  def create
    @user = User.find_by(username: params[:username])
    if @user&.authenticate(params[:password])
      session[:id] = @user.id
      redirect_to @user
    else
      render new_user_path
    end
  end

  def destroy
    raise params.inspect
    session.delete(:id)
    redirect_to root_url
  end
end

Upvotes: 1

Views: 46

Answers (1)

quyetdc
quyetdc

Reputation: 1585

By default when using resources :sessions, only: [:new, :create, :destroy], it will create route like DELETE /sessions/:id and trigger the destroy action of your controller.

Here, in your html

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

This does not generate the correct url for Rails router to trigger your desired action (cause you don't pass any params[:id] as defined by routes)

You can update your routes.rb like

resources :sessions, only: [:new, :create]

delete '/users/session', to: "sessions#destroy", as: :sign_out

And then, in your view

<%= link_to "Log Out", sign_out_path, method: :delete %>

Upvotes: 3

Related Questions