2

I'm using devise in a rails app I'm building. I'd like to get the ID of the user that is currently signed in, with current_user.id, in my controller, without passing it as a parameter from my view. Is there any way I can do this? Thanks

Rudi Thiel
  • 2,441
  • 6
  • 20
  • 32

1 Answers1

2

If you have installed Devise properly and have not broken something by overriding the Devise controllers, you should be able to access current_user.id from the controller. This method will only work if a user is signed in which you can test with the user_signed_in? method. Finally, this assumes that the resource name Devise is using is indeed user. That is the default, but it is possible to configure Devise to work with different resource names.

Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
  • @RT5754: The `current_user` method should be available in all controllers in the starter app you linked. – Tom Aranda Oct 19 '17 at 20:45
  • and if I created new controllers do I have to include devise or something in them to access tehese methods? – Rudi Thiel Oct 19 '17 at 20:46
  • If you follow the instructions in the Devise documentation, you should not have to do anything to make `current_user` available. – Tom Aranda Oct 19 '17 at 20:47
  • thanks for your answer. The answer on this post worked for me https://stackoverflow.com/questions/28804532/undefined-local-variable-or-method-current-user-using-devise-rails-3-2 – Rudi Thiel Oct 19 '17 at 20:56
  • That makes sense. Your question indicated that you wanted to access `current_user` in your controller, not in your model. I am not sure what your particular use case is, but I would generally recommend against trying to access `current_user` in your model. It is usually better to keep that logic in a controller or in a helper. Regarding the SO questions linked above, I would have put that logic in a helper. – Tom Aranda Oct 19 '17 at 21:02
  • I do want to use it in my controller. This solution works for accessing it there – Rudi Thiel Oct 19 '17 at 21:03