Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get "current user" in Rails

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
like image 810
Houdini Avatar asked Apr 18 '13 06:04

Houdini


2 Answers

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') %>
like image 82
sevenseacat Avatar answered Sep 20 '22 14:09

sevenseacat


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
like image 34
IKA Avatar answered Sep 18 '22 14:09

IKA