这很简单,只有当current_user id 等于来自users/:id/edit 的id 时,才使users/:id/edit 的链接可用。类似的,这应该在视图中:
<% @users.each do |user| %>
<% if current_user && (user.id == current_user.id) %>
<%= link_to 'edit', edit_user_path(user) %>
<% else %>
<%= link_to 'edit', '#' %>
<% end %>
<% end %>
还要检查控制器操作中编辑用户的权限。
def edit
if current_user && (current_user.id == params[:id])
# do the stuff
# ....
else
redirect_to :some_action
要重用此代码,您可以使用before_action 来检查您需要的每个操作中的用户权限。
在application_controller.rb写一个方法:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# some code here
def check_priveleges
unless current_user && (current_user.id == params[:id])
redirect_to root_path
end
end
# some code here
end
在users_controller.rb 写一个before_action:
class UsersController < ApplicationController
# some code here
before_action :check_priveleges, only: [:edit]
# this mean pass to the `edit` action only after :check_priveleges filter
def edit
# already pass through :check_privilege action in `ApplicationController`
end
end