Metalopholus Metalopholus - 4 months ago 8x
Ruby Question

New project with "rails new --api" -- missing ActionDispatch::Request

I'm trying to access the request object in app/controllers/application_controller.rb. My code is:

class ApplicationController < ActionController::API
include ActionView::Layouts
include ActionController::RequestForgeryProtection


before_action :require_login


def require_login
unless logged_in?
logger.log "#{request}"

def logged_in?

This results in the error:

comparison of String with 0 failed, highlighting the line logger.log "#{request}"

I thought it was a problem with the middleware not being loaded, so I tried to load it in config/application.rb:

config.middleware.use ActionDispatch::Request

But this results in another error:

undefined method 'call' for ActionDispatch::Request

I seem to keep having to add things back in since I used the --api option and it strips a lot of things out. But I don't know how to add back in access to the request option. Any help?


It looks like you are mis-using logger.log. In the simple example below, I have outlined three ways to approach this. If you want to use logger.log, you need to specify at minimum a severity level. That is the source of the comparison of String with 0 failed message you are receiving.

class ApplicationController < ActionController::API
  before_action :log_request

  def log_request
    logger.log request                     # This doesn't work"#{request}")              # This works
    logger.log(Logger::WARN,"#{request}")  # This works


Valid levels are: FATAL, ERROR, WARN, INFO, DEBUG.

Reference: (logger.log is an alias for logger.add)

Logger#add(severity, message = nil, progname = nil) { ... }