我最近观看了railscast剧集#250 Authentication from Scratch (revised),并且我正在进行注册/登录/注销操作。但是我正在创建一个从数据库中删除用户的操作,但我在尝试删除用户时遇到了一些错误。
users_controller.rb 删除/销毁操作如下所示,
def delete
# the below line calls the destroy method / action
self.destroy
end
def destroy
session[:user_id] = nil
# @user = User.find(params[:id])
@user.destroy
# User.find(parmas[:id]).destroy
# the below line didn't delete the current user :(
# @user = User.destroy
redirect_to :controller=>'users', :action => 'new'
end
当我尝试删除用户时,我在浏览器中收到的错误消息如下所示。
包含删除链接的页面如下所示: index.html.erb
<h1>Welcome
<% if current_user %>
<%= current_user.email %>
<% end %>
</h1>
<p>You have <%= current_user.credit %> credits.</p>
<!-- http://stackoverflow.com/questions/5607155/ -->
<%= link_to('Delete your account', :controller => 'users', :action => 'destroy') %>
的routes.rb
Rails.application.routes.draw do
# the below generated route is not necessary
# get 'sessions/new'
# delete user route
#get 'delete' => 'users#delete'
# shortened routes, per railscast comment
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
# get 'signup', to: 'users#new', :as 'signup'
# get 'login', to: 'sessions#new', :as 'login'
# get 'logout', to: 'sessions#destroy', :as 'logout'
resources :users
resources :sessions
root to: 'users#new'
# get 'users/new'
# the below line specifies JSON as the default API format
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :users
end
end
答案 0 :(得分:2)
您可能会收到NoMethodError,因为您从未设置@user
变量,该行已被注释掉:
def destroy
session[:user_id] = nil
# @user = User.find(params[:id]) <-- Commenting out this line was your problem
@user.destroy
更改为
def destroy
session[:user_id] = nil
@user = User.find(params[:id])
@user.destroy
你应该好好去。
编辑:您可能想要做的一件事是使用旧版的link_to,指定控制器和操作,并使用route helpers更改为新样式。在这种情况下,我相信您使用link_to 'Delete your account', current_user, :method => :delete
,但您可以通过运行rake routes
进行检查,它将根据您的routes.rb文件列出可用的帮助程序。
答案 1 :(得分:1)
嗯,我认为你应该让事情变得更简单,从最愚蠢的事情开始,这是有效的。首先,如果您将控制器用作资源,那么就不会有删除操作,只会销毁。
def destroy
User.find(params[:id]).destroy
session[:user_id] = nil
redirect_to new_user_path
end
P.S。我再次假设您已在resources :users
中设置了routes.rb
如果您有一堆get|post|put|delete
路由,请确保正确指向重定向。