Reputation: 525
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]
Upvotes: 1
Views: 1158
Reputation: 525
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
Upvotes: 2