2

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.

2 Answers 2

3

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 %>
2
  • Hm. When I tried this I got an error: "undefined method `correct_user?'". Sorry I'm new to Rails. Is what you provided short-hand or something? I'm still not sure how it would recognize the logged in user with the correct user. Commented Nov 6, 2012 at 4:57
  • where are you define method correct_user? ? It should put in users_helper.rb, and do you have a method called current_user? what authentication system are you using, or you built your own?
    – Thanh
    Commented Nov 6, 2012 at 5:02
2

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.