如何将编辑操作限制为仅当前用户

How to restrict edit action to only current user

如何才能使用户编辑操作仅在用户是当前用户时才可用?我正在使用设计。

Devise 有这个:

before_action :authenticate_user!, only: [:new, :edit, :update, :destroy], notice: 'you must sign in first!'

但这一切只是为了确保用户已登录,而不是如果用户等于当前用户?我想确保其他用户无法编辑其他用户帐户。

最好的方法是什么?我应该创建一个新的 before_filter 吗?我找不到任何标准方法。

我强烈建议查看 CanCanCan gem 来处理这些事情。在这种情况下,您的代码将类似于:

查看:

<% if user_signed_in? %>
  <% if can? :update, @user %>
    # Edit something 
    <%= link_to edit_profile_path(@user), class: 'user' do %>
      Edit your profile
    <% end %>
  <% end %>
<% end %>

并且在您的用户控制器或类似的控制器中,您将添加以下行来处理用户手动向浏览器键入 url 的情况:

控制器:

class UsersController < ApplicationController
   load_and_authorize_resource
   ...

更多信息和文档:https://github.com/CanCanCommunity/cancancan

可以使用devise提供的current_user方法。在这里你可以阅读更多-current_user method.

def edit
  unless current_user 
    redirect_to home_path, :alert => "Restricted area" 
  end
end