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

2
  • 3
    I must ask it, have you tried using current_user.id? Oct 19, 2017 at 20:23
  • @Sebastián Palma yes I tried it and got tihs error: undefined method `id' for nil:NilClass
    – Rudi Thiel
    Oct 19, 2017 at 20:38

1 Answer 1

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.

6
  • @RT5754: The current_user method should be available in all controllers in the starter app you linked.
    – Tom Aranda
    Oct 19, 2017 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, 2017 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, 2017 at 20:47
  • thanks for your answer. The answer on this post worked for me stackoverflow.com/questions/28804532/…
    – Rudi Thiel
    Oct 19, 2017 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, 2017 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.