Search code examples
ruby-on-railsstrong-parametersgrape-api

Grape: ActiveModel::ForbiddenAttributesError


When calling my API Endpoint, I am getting this error:

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

day_points_api.rb

module V1
  class DayPointsApi < Grape::API
    namespace 'api/v1' do
      resource :points do
        desc 'start all metrik jobs'

        params do
          requires :product, type: String
          requires :type, type: String
          requires :value_at, type: Date

          requires :points, type: Array do
            requires :platform, type: String
            requires :country, type: String
            requires :value, type: Float
          end
        end

        post do
          params[:points].each do |point|
            point_params = point.merge(params.except(:points))
            DayPoint.constantize.import(point_params)
          end
        end
      end
    end
  end
end

Clearly, this is due to StrongParameter - but to be honest, I already define what parameters are required - these should be the only ones allowed by default.

There are some solutions available using helper methods - which I find are ugly.

How is this possible? Are there alternatives?


Solution

  • After searching the internet everywhere else, I found the solution in the official Grape Docs - what a champ! /sarcasm

    If the version of your Rails is 4.0+ and the application uses the default model layer of ActiveRecord, you will want to use the hashie-forbidden_attributes gem. This gem disables the security feature of strong_params at the model layer, allowing you the use of Grape's own params validation instead.

    I added this to SO to help anyone who should stumble like me.