在rails上的ruby中注销并删除用户

时间:2016-01-04 03:31:56

标签: ruby-on-rails

在我的ruby on rails网站上,我希望用户只是临时的,所以每次用户注销时,我都希望它也从数据库中删除用户。我该怎么做?

链接到注销,我希望这也从数据库中删除当前用户:

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

会话控制器:

class SessionsController < ApplicationController

  before_action :require_none, only: [:new]

  def new
  end

  def create
    @user = User.find_by_username(params[:session][:username])
    if @user && @user.authenticate(params[:session][:password])
      session[:user_id] = @user.id
      redirect_to '/home'
    else
      redirect_to '/login'
    end 
  end

  def destroy      
    session[:user_id] = nil     
    redirect_to '/forsale' 
  end  

end

用户控制器:

class UsersController < ApplicationController

  before_action :require_none, only: [:new]

  def new
    @user = User.new
  end

  def create 
    @user = User.new(user_params) 
    if @user.save 
      session[:user_id] = @user.id 
      redirect_to '/home' 
    else 
      redirect_to '/signup' 
    end 
  end 

  private
    def user_params

      params.require(:user).permit(:name, :username, :password);
    end

end

的routes.rb

Rails.application.routes.draw do

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'welcome#index'

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'
  get '/logout' => 'sessions#destroy'
  resources :sessions


  get 'signup'  => 'users#new' 
    resources :users

  get '/home' => 'home#view'

  get '/forsale' => 'forsale#view'

  get '/contact' => 'contact#view'

  get '/about' => 'about#view'

end

1 个答案:

答案 0 :(得分:4)

如果您想在注销时销毁用户记录,那么在给出当前代码的情况下,您可以直接执行此操作

class SessionsController < ApplicationController
  ...
  def destroy
    User.find(session[:user_id]).destroy      
    session[:user_id] = nil         
    redirect_to '/forsale' 
  end  
end