如果我有一个像下面这样的控制器,保护我的表演行为的最好方法是什么?当前设置的方式--任何用户都可以使用id查看另一个用户的备注。
class NotesController < ApplicationController
before_action :authenticate_user!
def index
@notes = Note.where(user_id: current_user)
end
def show
@note = Note.find(params[:id])
end
def new
@note = current_user.notes.build
end
end发布于 2017-01-29 04:36:52
方法: 1
def show
@note = Note.find(params[:id])
redirect_to anywhere_you_want, notice: "can't see others note" if @note.user != current_user
end方法: 2
创建一个before_action,如:
before_action :authenticate_note_user, only: [:show]
private
def authenticate_note_user
@note = Note.find(params[:id])
redirect_to anywhere_you_want, notice: "can't see others note" if @note.user != current_user
end发布于 2017-01-29 11:10:33
身份验证是一回事,但授权现在已经相当another.Right了(如果我对您的理解是正确的),如果有任何用户登录,他们可以查看其他人的凭据等等,您不想这样做。这可以理解。
您将不得不实现CanCanCan -或类似的gem。在大约30-45分钟的时间里,你可以把它定位出来,并为你想要的任何东西设置权限。
https://github.com/CanCanCommunity/cancancan
http://railscasts.com/episodes/192-authorization-with-cancan
请注意,CanCan已经过时,不再维护。
如果您需要CanCanCan的帮助,您可以随时重新发布,但这是非常简单的。
https://stackoverflow.com/questions/41917384
复制相似问题