Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 564
deefour Avatar asked Dec 06 '12 14:12

deefour


2 Answers

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
like image 61
deefour Avatar answered Sep 21 '22 22:09

deefour


This problem can be solved by including the rails_api master git branch in your Gemfile as below:

gem 'rails-api', git: 'https://github.com/rails-api/rails-api.git', branch: 'master'

rails_api gem has fixed this issue by including the below lines at api.rb

if Rails::VERSION::MAJOR == 4
   include StrongParameters
end
like image 34
user2801 Avatar answered Sep 18 '22 22:09

user2801