Reputation: 1113
I rather clumsily replaced my own auth system (based on Michael Hartl's tutorial) with the Devise gem today.
I've got most things working again but have a lot of errors relating to use of current_user
.
This, for instance, doesn't work any more:
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
I previously had current_user defined in a sessions helper as follows:
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
end
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
I've done away with that, thinking that devise provided the same functionality but that doesn't seem to be the case. In almost all of the situations where I was previously using current_user I now get undefined method
current_user?'`. I'm hoping there is something global I can do to make the old usages work?
Any pointers much appreciated. I've had by far my worst day of rails in the six months I've been using it.
EDIT: The comments explain that I no longer have current_user?
defined. I've tried adding the following to my users_controller but it doesn't seem to have worked:
def current_user?(user)
user == current_user
end
Upvotes: 1
Views: 957
Reputation: 3410
You deleted your current_user?(user)
method with sessions_helper
. Now Devise do all the necessary for you, but Devise has only current_user
method, no current_user?(user)
.
You can define it by yourself in any helper, methods from all of them works in any view and any controller.
In fact, if you have many conditions, where you need to check if user is admin, and user isn't a current_user. You can make a separate helper for it. But, as I remember from Michael Hartl's tutorial, there is not many such blocks (:
Something like:
def not_admin?(user)
current_user.admin? && !current_user?(user)
end
So, you can refactor you view:
<% if not_admin?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
Also you can make it more clear with:
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } if not_admin?(user) %>
Upvotes: 1