需要允许用户删除自己的个人资料 - Rails,Devise,Cancan

时间:2014-06-17 13:02:33

标签: ruby-on-rails ruby devise cancan

经过几个小时的尝试拼凑我在这里和网络上找到的代码之后,我想我已经到了可能弄乱了我的代码的地步。如果您需要任何其他代码段,请告诉我,我将尝试在下面提供相关代码。用户和个人资料有单独的模型。

感谢您的帮助!

编辑:rake路线显示此路线:  admin_destroy_user DELETE /users/:id(.:format)profiles#destroy

我在尝试加载编辑个人资料页面时遇到此错误(localhost:3000 / settings / profile): "没有路线匹配{:controller =>" devise / profiles",:action =>" destroy"}"

_form.html.haml

.row
  .span6
    .actions
      = f.submit 'Save', class: 'btn-submit'
      = link_to 'Delete Account', admin_destroy_user_path, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn-delete'
      = link_to 'Cancel', profile_index_path

profile_controller

def destroy
  @user = User.find(params[:id])
  @user.destroy

  if @user.destroy
    redirect_to root_url, notice: "User deleted."
  end
end

的routes.rb

devise_for :users    
match 'users/:id' => 'devise/registrations#destroy', :via => :delete, :as =>    :admin_destroy_user
match 'users/:id' => 'user#show', as: :user
resources :users

ability.rb

if user.is? :admin
  can :access, :admin #access the admin page
  can :manage, :all #do anything to any model
else
  can :read, :all #read any model
  can [:update, :destroy], Profile, :user_id => user.id

2 个答案:

答案 0 :(得分:1)

在你的ProfileController中,你销毁了错误的对象。目标应该是个人资料,但不是用户。

所以它应该是这样的

def destroy
  @profile = Profile.find(user_id: params[:id])
  if @profile.destroy
    redirect_to root_url, notice: "User deleted."
  else
    render_error_message
  end
end

但是,我真的无法找到删除个人资料的任何要点。如果配置文件为空,只需将其显示为空,就像StackOverflow显示的那样,这是正常的。

答案 1 :(得分:0)

我得到了它的工作!我将粘贴下面代码中的更改。当单击删除按钮时,用户及其配置文件(两个单独的型号)将删除此选项。

<强> _form.html.haml

user_registration_path,

<强> profile_controller

def edit
  @user = current_user
end

def destroy
  @user = current_user
  @profile = current_user.profile
  if @profile.destroy
    @user.destroy
    redirect_to root_url, notice: "User deleted."
  else
    render_error_message
  end
end

<强> ability.rb

  can :manage, User do |u|
    u.id == user.id
  end