In the /views/layouts
directory, how do I get the current user? I am using Devise, but current_user
does not work here for some reason, it describes it as an unknown method. I want to do something like:
<% if User.role? == "gen_admin" %>
<li>
<%= link_to('Admin', users ) %>
</li>
<% end %>
I do have a role?
method defined in my User model, but I still get this exception:
undefined method 'role?' for #<Class:0x3fcc1e0>
So how can I get the current user, and access its fields at this level of the source tree? Thanks!
Here is the roles? method:
# in User
ROLES = %w[gen_admin teacher_admin student]
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
Your code must account for when users are logged in, and when they are not logged in.
If no user is logged in, then current_user
will return nil (as in your case, which you thought was an error on Devise's part).
Your view code must handle this - eg.
<% if current_user.present? && current_user.role?('gen_admin') %>
You have defined your role?
method as an instance method. This means that in order to use it you should first create the instance from User
class e.g.:
@user=User.new
Now you can call @user.role?
If you want role?
to be available through the model User
then you should define it as class method an pass in an object for verification
def self.role?(user)
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With