我正在尝试将Devise和Cancan合并到一个网络应用程序中。我想要用户:role => “admin”能够删除用户,而Devise的destroy操作只允许用户自行删除,因此我为此创建了一个自定义操作。 (要覆盖插件的控制器文件,我已将注册控制器复制到app / controllers / registrations_controller.rb。)
这是我在registrations_controller.rb中的自定义操作:
def destroy_user_account
@user = User.find_by_id(params[:user])
@user.destroy
redirect_to profiles_path, :flash => { :success => "User deleted!" }
authorize! :destroy, User, :message => "You don't have authorisation to delete this user."
end
以下是我尝试使用它的方法,在您查看用户个人资料的页面上的链接中。 (我设置了一些东西,以便每个用户都有一个配置文件;配置文件是您在前端看到的。配置文件会在用户注册的配置文件表中自动创建。)
<% if can? :update, @profile %>
| <%= link_to 'Edit Profile', edit_profile_path(@profile) %>
| <%= link_to 'Edit Settings', edit_settings_path %>
<% end %>
<% if can? :destroy, @profile.user %>
| <%= link_to "Delete User", destroy_user_account(@profile.user),
:class => "delete",
:confirm => "Are you sure?",
:title => "Delete #{@profile.user.name}"
%>
<% end %>
我的测试显示了2个我无法解决的失败:
1)ProfilesController GET以管理员身份登录时显示 有一个编辑个人资料的链接 失败/错误:get:show,:id =&gt; @轮廓 ::的ActionView ::模板错误: 未定义的方法
destroy_user_account' for #<#<Class:0x105b474a8>:0x1057f32e8> # ./app/views/profiles/show.html.erb:41:in
_ app_views_profiles_show_html_erb___917863454_2195331000_0' #./spec/controllers/profiles_controller_spec.rb:1432)ProfilesController GET以管理员身份登录时显示 有一个删除用户帐户的链接(使用 注册控制器中的destroy_user_account操作) 失败/错误:get:show,:id =&gt; @轮廓 ::的ActionView ::模板错误: 未定义的方法
destroy_user_account' for #<#<Class:0x105b474a8>:0x105806d20> # ./app/views/profiles/show.html.erb:41:in
_ app_views_profiles_show_html_erb___917863454_2195331000_0' #./spec/controllers/profiles_controller_spec.rb:148
另外,当我在浏览器中试用它时,点击“删除用户”链接会出现以下错误:
路由错误
没有路线匹配“/ destroy-user-account / 2”
以下是应该涵盖的路线:
devise_for:users,#:path =&gt; ', :skip =&gt; [:确认,:密码,:注册], :controllers =&gt; {:registrations =&gt; “注册”}做
# Routes for ACCOUNT REGISTRATIONS get "join", :to => "registrations#new", :as => :new_user_registration post "join", :to => "registrations#create", :as => :user_registration get "settings/account", :to => "registrations#show", :as => :settings get "settings/account/edit", :to => "registrations#edit", :as => :edit_settings put "settings/account", :to => "registrations#update", :as => :update_settings delete "close-my-account/:id", :to => "registrations#destroy", :as => :close_my_account delete "destroy-user-account/:id", :to => "registrations#destroy_user_account", :as => :destroy_user_account
任何人都可以帮我解决我的错误吗?
答案 0 :(得分:0)
在浏览器中,它与路由不匹配,因为您发送了GET
请求,但该路由仅匹配DELETE
请求。测试失败,因为路由提供了名称destroy_user_account_path
而不是destroy_user_account
。
尝试:
<%= link_to "Delete User", destroy_user_account_path(@profile.user),
:class => "delete",
:confirm => "Are you sure?",
:title => "Delete #{@profile.user.name}"
:method => :delete
%>