Mitch Malone
Mitch Malone

Reputation: 399

Display edit user link only when that user is logged in

I have a Users resource and I want to display the "edit" link in the show.html.erb files only when that user is logged in. See screenshots.

Here is a list of users. Notice in the top right that Roger Sterling is logged in.

Here is a list of users. Notice in the top right that Roger Sterling is logged in.

But if I click on Don Draper, the show.html.erb file displays the "Edit" button. I only want that to appear for Roger Sterling, in this case.

But if I click on Don Draper, the show.html.erb file displays the "Edit" button. I only want that to appear for Roger Sterling, in this case.

I'm using Devise for authentication. Any ideas on how to accomplish this? Let me know if you need to see any available code.

Upvotes: 2

Views: 1569

Answers (2)

Mitch Malone
Mitch Malone

Reputation: 399

Ha. Ok I got it.

Here is the loop in the show.html.erb file:

<% if (@user.name == current_user.name) %>
    <%= link_to 'Edit', edit_user_registration_path(@user) %> 
<% end %>  

And the helper method:

def correct_user
    user == current_user
end

Thanks for the push in the right direction!

Upvotes: 2

Thanh
Thanh

Reputation: 8604

You can check current_user and user is shown, if they are the same, the link 'Edit' will display. You can define a helper method like this:

def correct_user?(user)
  user == current_user
end

In your show action of UsersController will have:

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

and in your view, you can check:

<% if correct_user?(@user) %>
  <%= link_to 'Edit', @user %>
<% end %>

Upvotes: 3

Related Questions