0

I use devise for authentication. In my User model there is a field "locale", which I want to use in the application controller for the current logged in user. So I have this in the application controller:

    @user = User.current_user.locale

But this doesn't work. How can I access fields of the current user in the application controller? And devise hasn't created a users controller, where can I find that when I want to make some changes there? Thanks!

John
  • 6,404
  • 14
  • 54
  • 106

4 Answers4

2

current_user is already User object, just call locale on it :

@user = current_user
locale = current_user.locale
Elmatou
  • 1,324
  • 12
  • 18
0

current_user is available as usual in the application controller. to access it in every request (in your application controller):

before_filter :get_locale

def get_locale
  @user = current_user
  locale = @user.locale
end
Nuriel
  • 3,731
  • 3
  • 23
  • 23
0

current_user is not available in application_controller as it extends base. Simple solution is to use it like that

before_action :user_full_name

def user_full_name
 @user_full_name = current_user.fname + ' ' + current_user.lname
end
Sajidur Rahman
  • 2,764
  • 1
  • 27
  • 26
0

current_user is an instance method, meaning you can only call it on (or within) an instance of the User class. When you do User.current_user you're trying to call it as a class method, i.e. a method on the User class itself.

If you really need to use current_user within ApplicationController--at best a code smell and at worst a really bad idea--you can fall back on Warden, which Devise is built on top of. E.g.:

user = env['warden'].current_user
user.locale

As for your other question regarding controllers, it has been answered before.

Community
  • 1
  • 1
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • That's not working: undefined method `current_user' for # – John Oct 06 '11 at 09:51
  • Ah, having not worked with Warden directly before I may have been wrong, or anyway can't solve that. Could you back up and show us the code you would like to put in `ApplicationController`, and tell us why it's most appropriate there rather than in another controller? – Jordan Running Oct 06 '11 at 10:04
  • #Jordan, I think your are wrong, Devise set current_user as an helper (returning an instance variable) for ApplicationController, allowing to access it directly in controller and views. It is not related with warden (even if it is build using warden env). – Elmatou Oct 06 '11 at 12:02