Search code examples
ruby-on-railsrails-apistrong-parameters

Getting rails-api and strong_parameters to work together


When including

gem 'strong_parameters'
gem 'rails-api'

together in my Gemfile, calling params.require like

private
  def user_params
    params.require(:user).permit(:first_name, :last_name)
  end

fails with the following error on the require() call.

TypeError:
   can't convert Symbol into String

The backtrace shows strong_parameters' ActionController::StrongParameters' require() method is never hit.


Solution

  • I spent too long on this one, so I figured I'd share here to hopefully save someone else a bit of time.

    The error above comes from the require() method in ActiveSupport::Dependencies::Loadable being executed when calling

    params.require(:user)...
    

    strong_parameters injects ActionController::StrongParameters into ActionController::Base at the bottom of this file with

    ActionController::Base.send :include, ActionController::StrongParameters
    

    The rails-api gem requires your app's ApplicationController extend ActionController::API in favor of ActionController::Base

    The application controllers don't know anything about ActionController::StrongParameters because they're not extending the class ActionController::StrongParameters was included within. This is why the require() method call is not calling the implementation in ActionController::StrongParameters.

    To tell ActionController::API about ActionController::StrongParameters is as simple as adding the following to a file in config/initializers.

    ActionController::API.send :include, ActionController::StrongParameters