Reputation: 427
I'm following Ruby on Rails Tutorial by Michael Hartl. I have reached chapter 9. There are some codes that I don't understand. Please see below, line 4, why do we need a !
in front of current_user?(user)
to make it !current_user?(user)
Didn't we need true && true
for the if statement to pass so Admin can see the delete action.
If a user logged in and is a admin, then current_user.admin? == true
, current_user?(user) = true
, and !current_user?(user)
will be false and the if statement won't pass.
_user.html.erb
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,data: { confirm: "You sure?" } %>
<% end %>
</li>
sessions_helper.rb
def current_user=(user)
@current_user = user
end
def current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def current_user?(user)
user == current_user
end
Thanks in advance.
Upvotes: 1
Views: 351
Reputation: 20560
Only Admins can delete users and they can't delete themselves.
From railstutorial.org Chapter 9.4:
administrative users should see such links, and by clicking on a delete link we expect an admin to delete the user
and
Note also that we have added a test to verify that the admin does not see a link to delete himself
So:
current_user.admin?
means "is the current user an admin?"
!current_user?(user)
means "is the current user different from the user I am displaying?"
Put together, <% if current_user.admin? && !current_user?(user) %>
as a test for displaying the Delete
link means that the delete link only displays for Admins but not when their own user
details are being displayed. That is, only Admins can delete users and they can't delete themselves.
Remember, the user view is displaying a list of the users, not just the current user. In this context, user
means the model of the user that is being displayed by the view at that time.
Check this image and note that Example User
does not have a delete link but everyone else does.
Upvotes: 2