Rails & Devise: How to authenticate specific user?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

I'm using Devise for the first time with rails, and I'm having trouble with one thing: I used the provided authenticate_user! method in my user's controller to restrict access to pages like so: before_filter :authenticate_user!, :only => [:edit, :show, :update, :create, :destroy]

But this allows any signed in user to access any other users :edit action, which I want to restrict to only that user. How would I do that?

回答1:

In your edit method, you need to do a check to see if the user owns the record:

def edit    @record = Record.find(params[:id])    if @record.user == current_user       @record.update_attributes(params[:record])    else       redirect_to root_path    end end 


回答2:

You should look into Authorization such as CanCan. Or alternatively create a new method like so:

# Create an admin boolean column for your user table.  def authenticate_admin!   authenticate_user! and current_user.admin? end 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!