无法从rails中删除用户

时间:2015-09-12 06:11:17

标签: ruby-on-rails

我正在尝试从我的rails应用程序中取消激活用户。但是,目前这不起作用。

我的路线档案 -

# Root is the unauthenticated path
root 'sessions#unauth'

# Sessions URL
get 'sessions/unauth', to: 'sessions#unauth', as: :login
post 'sessions/login', as: :signin
delete 'sessions/logout', as: :logout

# Resourceful routes for articles
resources :articles
get '/interests', to: 'articles#my_interests', as: 'interests'
get '/destroy', to: 'users#destroy', as: 'destroy_user'
resources :users, only: [:create,:new,:update,:destroy,:edit]

然后我在布局文件夹中有一个html文件。

<li><%= link_to "De-activate User", destroy_user_path(current_user)%></li>

用户将单击“取消激活用户”按钮,我希望操作进入我的用户控制器。下面是我的UsersController.rb。

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user, only: [:edit, :destroy, :update]
  before_action :check_valid, only: [:edit, :destroy, :update]
  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    log_out @user
    @user.destroy
    respond_to do |format|
      format.html { redirect_to login_path, notice: 'user was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    def check_valid
      unless @user==current_user
        redirect_to articles_path
      end
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:first_name, :last_name, :email, :bio, :username, :password, :interest_list, :password_confirmation)
    end
end

Rails在set_user方法中给出了错误。 错误 - 找不到'id'= @ user = User.find(params [:id])

的用户

我无法理解这里的问题是什么?

我的log_out方法 -

def log_out
    session[:user_id] = nil
end

3 个答案:

答案 0 :(得分:1)

试试这个

<li><%= link_to "De-activate User", destroy_user_path(current_user), method: :delete%></li>

由于

答案 1 :(得分:0)

您已覆盖由resources :users生成的默认路径:

get '/destroy', to: 'users#destroy', as: 'destroy_user'

如果您正确看到自己建造的路线,则无法找到params[:id]。通过这条路线,您可以采取行动但在那里找不到params[:id]

您可以像这样更改路线:

get '/destroy/:id', to: 'users#destroy', as: 'destroy_user'

所以你的cuurent代码将正常工作。

答案 2 :(得分:0)

请试试这个:

<%= link_to "De-activate User", current_user, method: :delete %>

OR

<%= link_to "De-activate User", user_path(current_user), method: :delete %>