Rails & Devise: How to authenticate specific user?

2020-06-23 07: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