Devise methods undefined in Rails project

2019-09-02 08:09发布

问题:

I have a Rails 5 app with the Devise gem installed. My project is set up in such a way, that all controllers are namespaced...Even Devise controllers.

In my routes file I have done this(This will better explain my namespacing structure):

controllers: {
    sessions: "api/v1/public/members/users/sessions",
    passwords: "api/v1/public/members/users/passwords",
    registrations: "api/v1/public/members/users/registrations",
},
path_names: { 
  sign_in: 'login', 
  password: 'forgot', 
  sign_up: 'register',
  sign_out: 'signout'
}

I have also setup the devise view files to reflect the required namespaced structure.

I have included the following in my ApplicationController.rb:

before_action :authenticate_api_v1_public_members_user!

Since my Devise controllers are namespaced, the standard 'before_action :authenticate_user!' method needed to be updated to the one above in order to work.

The issue that I'm experiencing, is that none of the Devise helper methods are available in any of my views. When calling 'current_user' or 'user_signed_in?' in a view, I am presented with an 'undefined method' error when refreshing my browser. I tried namespacing these helper methods as well, but to no avail.

UPDATE Models are not namespaced in my app. I am using a normal User model. Only controllers are namespaced and are structured as indicated by the route above.

Does anybody have experience with a similar issue?

回答1:

It seems to be that Devise is nested within the :api_v1_public_members namespace in your routes.rb. In this case it affects not only on authenticate_user! method, changing it into authenticate_api_v1_public_members_user!, but on the others methods too.

  • current_user turns to current_api_v1_public_members_user

  • user_signed_in? turns to api_v1_public_members_user_signed_in?

There is similar problem here undefined method `authenticate_user! Api::PostsController in Devise / Rails 4