When versioning via modules, why isn't me method being recognized and sending a NoMethodError?

StackOverflow https://stackoverflow.com/questions/23658830

Pergunta

In controllers/api/v1/sessions_controller.rb I have...

module Api
    module V1
        class SessionsController < ApplicationController
            respond_to :json
            skip_before_filter :verify_authenticity_token

            def create
                @user = User.find_by(email: params[:session][:email].downcase)
                if @user && @user.authenticate(params[:session][:password])
                    token = User.new_remember_token
                    sign_in @user, token

and then in helpers/api/v1/sessions_helper.rb I have...

module Api
    module V1
        module SessionsHelper
            def sign_in (user, token)
                user.update_attribute(:remember_token, User.digest(token))
                self.current_user = user
            end
        end
    end
end

When I attempt to POST to Sessions, I get the following error.

NoMethodError (undefined method `sign_in' for #<Api::V1::SessionsController:0x0000010324d278>):
  app/controllers/api/v1/sessions_controller.rb:12:in `create'

Why am I getting this error? Is this not correct?

Foi útil?

Solução

Methods defined in helper classes of a resource are directly accessible only in corresponding views(of the same resource) and NOT in controller, so you would need to include the helper module explicitly in the controller in order to access these helper methods.

module Api
    module V1
        class SessionsController < ApplicationController
          include Api::V1::SessionsHelper ## Add this
          ## ...
        end
    end
end 

You are getting the error because Api::V1::SessionsController has no idea about the existence of sign_in method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top