简体   繁体   中英

Destroy user session without Devise Rails 5

I will try to do a simple user authorization without Devise. My session controller has new, create and destroy actions:

  def new
    @user = User.new
  end

  def create
    @user = User.find_by(name: user_params[:name])
    @user ||= User.create(user_params)
    if @user.valid? && @user.authenticate(user_params[:password])
      session[:user_id] = @user.id
      redirect_to tasks_path
    end
  end

  def destroy
    reset_session
  end

But it doesn't work. How can I destroy a user session?

Something like this should do it. It really depends on what kind of helpers you have set up. You'll need access to the session variable you created and also the user id, so session.delete(@user.id) might end up being what you need. Depends on how this is being sent over to the method and what data you have access to (is there a before action or something providing the @user variable or do you need to find it with something like @user = User.find(:params) where params is the user id.

def destroy
  session.delete(:user_id)
  @user = nil
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM