Search code examples
ruby-on-railsrubyruby-on-rails-4model-view-controllerattr-accessor

How to make attribute set in model method available in controller? attr_accessor not working?


My sessions controller method (for an API) uses a model method to generate a token. Next it should send the token to the front end using json. However, at the render json line, the api_token isn't available anymore and is nil. How should one handle this?

module Api
  module V1
    class ApiSessionsController < Api::BaseController
      def create
        user = User.friendly.find_by(email: create_params[:email].downcase)
        if user && user.authenticate(create_params[:password])
          user.create_api_token
          render json: { api_token: api_token }, status: :ok
        else
          render json: {errors: "wrong credentials" },  status: :unauthorized
        end
      end
   end 
  end 
end

class User < ActiveRecord::Base
    attr_accessor :api_token
    has_secure_password

    def create_api_token
      begin
        self.api_token = User.new_token
        api_digest = User.digest(api_token)
      end while self.class.exists?(api_digest: api_digest)
      update_attributes(api_digest: api_digest, api_sent_at: Time.zone.now)
    end

    def User.digest(string)
      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
      BCrypt::Password.create(string, cost: cost)
    end
end

Solution

  • I believe the line should look like

    render json: { api_token: user.api_token }, status: :ok
    

    Your controller code references to api_token variable which is not defined and hence you receive nil