ForbiddenAttributesError with Grape and ActiveRecord

1k views Asked by At

I have a ruby application using Grape, and it doesn't have rails.

class Article < ActiveRecord::Base
end

class API::Articles < Grape::API
  post '/articles' do
    article = Article.create(params[:article])
  end
end

Article.create gives ActiveModel::ForbiddenAttributesError:

There is some discussion about it here, but I don't understand it. I've tried this suggestion:

post '/articles' do
  article = Article.create(permitted_params[:article])
  represent(article, env)
end

helpers do
  def permitted_params
    @permitted_params ||= declared(params, include_missing: false)
  end
end

This time @permitted_params is empty so attributes are gone.

I've also tried wrapping th hash with ActionController::Parameters, but that fails with other errors.

What is the suggested solution to solve ForbiddenAttributesError, in Grape as of now?

Grape uses hashie gem for params, and their solution for this is to include a gem called hashie_rails, but this gem brings all the rails with it, but I don't want any of that. So I need a vanilla solution.

2

There are 2 answers

0
user3995789 On

https://gist.github.com/smd686s/6320643

Gemfile

gem "actionpack", "~> 4.0.0"

app.rb

require 'rack/test'
require 'action_controller/metal/strong_parameters'

#https://github.com/rails/rails/blob/master/actionpack/test/controller/parameters/parameters_require_test.rb

module Application
  class API < Grape::API

    helpers do
      def item_params
        ActionController::Parameters.new(params).require(:item).permit(:attribute)
      end
    end

    desc "Create an item."
    post :items do
      Item.new item_params
    end
  end
end
0
Tyler Collier On

You need to use the hashie-forbidden_attributes gem as mentioned in the grape documentation:

Additionally, 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.