robb
robb

Reputation: 294

Showing edit button to current_user only (Rails 4)

I'm trying to allow users to show the edit button only if the profile belongs to them. Currently, they're only allowed to edit the profile if it belongs to them but I can't seem to hide the button. I have this so far

<% if request.original_url == request.base_url + "current_user.id" %>
  <%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs" %>&nbsp;
<% end %>

This is what I'm trying to compare:

request.original_url => localhost:3000/users/random_user

request.base_url + "users/" + current_user.id => localhost:3000/users/current_user

Thanks in advance.

Upvotes: 1

Views: 1232

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Authorization

To give you some perspective, you'll be looking for something called authorization.

This is different from authentication because it deals with permissions, rather than identifying your identity. I'll get into how this works in a minute.


To solve your problem, here's what you need to do:

<%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs", if user_signed_in? && current_user == @user %>

I'm guessing you're showing this on a user#show action, which can be invoked using the following code:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def show
      @user = User.find params[:id]
   end
end

This means that if you have the following routes:

#config/routes.rb
resources :users

you'll have access to @user and current_user. It's important to note that current_user != @user. Although weezing's answer is succinct, it does not validate whether the user is the one which owns the page authorized; just that the user is authenticated


Thus, you have several specifications:

  1. You need to know if the user is actually logged in
  2. You need to make sure your logged-in user has the authorization to edit the profile (IE is it theirs)

I would highly recommend looking into the use of gems such as CanCanCan or Pundit. I'll show you CanCanCan:

#app/models/ability.rb
class Ability
   include CanCan::Ability

   def initialize(user)
      user ||= User.new # guest user (not logged in)
      can :edit, Article, id: user.id
   end
end

#app/views/users/show.html.erb
<%= link_to "Edit", edit_user_path(@user) if can? :edit, @user %>

There is a great resource here.

Upvotes: 4

weezing
weezing

Reputation: 396

This should work (little bit simpler):

<% if current_user %>
  <%= link_to "Edit Profile", edit_user_path(current_user), class: "btn btn-primary btn-xs" %>
<% end %>

Upvotes: 0

Related Questions