简体   繁体   中英

Rails: Current user should only be able to view their own users#show page (Devise)?

Is there a way to allow a user to only view their own profile page (users#show)? So when someone with an id of say 1 tries to go to the www.myapp.com/users/ 412 url, he will be re-directed to the root page? He can only access www.myapp.com/users/ 1 .

I am using devise and this is what I've tried. However with this code strangely enough, the current user cannot access his own page.

users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!
  before_action :only_see_own_page, only: [:show]

  def show
    #some ruby code here
  end

  private

  def only_see_own_page
    if current_user.id != params[:id]
      redirect_to root_path, notice: "Sorry, but you are only allowed to view your own profile page."
    end
  end
 end

**routes.rb*

resources :users, only: [:show]

Argh, it was that easy... This is what worked for me:

def only_see_own_page
  @user = User.find(params[:id])

  if current_user != @user
    redirect_to root_path, notice: "Sorry, but you are only allowed to view your own profile page."
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM