【问题标题】:Need to allow user to delete own profile - Rails, Devise, Cancan需要允许用户删除自己的个人资料 - Rails、Devise、Cancan
【发布时间】:2014-06-17 13:02:32
【问题描述】:

在尝试将我在这里和整个网络上找到的代码拼凑几个小时之后,我想我已经到了可能把我的代码弄得一团糟的地步。如果您需要任何其他 sn-ps,请告诉我,我将尝试在下面包含相关代码。用户和个人资料有不同的模型。

感谢您的帮助!

编辑:rake route 显示这条路线: admin_destroy_user 删除 /users/:id(.:format) 个人资料#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

【问题讨论】:

    标签: ruby-on-rails ruby devise cancan


    【解决方案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
    

    但是,我真的找不到删除个人资料的任何要点。如果profile是空的,就按照StackOverflow显示的那样显示为空,这很正常。

    【讨论】:

    • 嗨,比利,感谢您的回答。我已经在我的代码中实现了它;但是,我无法加载页面以进行尝试(请参阅上面的编辑与路由错误)。我的雇主希望用户能够删除他们的帐户。如果您有更好的实现方式,请告诉我!
    【解决方案2】:

    我让它工作了!我将在下面粘贴我的代码中的更改。单击删除按钮时,这将由用户及其个人资料(两个单独的模型)删除。

    _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
    

    【讨论】:

    • 大卫,很高兴你开始工作了。满足要求就好了。
    • 为了未来的改进,我建议 1) 将销毁路由到用户而不是配置文件,因为您真正需要的是销毁帐户而不是配置文件。您可以使用dependent :destroy 设置关联。 2)永远不要真正立即销毁东西,尤其是敏感信息,而是使用软删除解决方案,销毁记录,将其数据保存在其他地方,并在几天后完全销毁它。一个月。
    • 太棒了,谢谢比利。如果不是很明显,我对 Rails 开发还很陌生,并且正在从事一个已经上线的相当大的项目。我很感激你的建议。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多