葡萄:ActiveModel::ForbiddenAttributesError

Grape: ActiveModel::ForbiddenAttributesError

调用我的 API 端点时,出现此错误:

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

显然,这是由于 StrongParameter - 但老实说,我已经定义了需要哪些参数 - 这些应该是唯一允许的参数。

有一些可用的解决方案using helper methods - 我觉得很丑。

这怎么可能?有其他选择吗?

在其他地方搜索互联网后,我在 official Grape Docs 中找到了解决方案 - 太棒了! /讽刺

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.

我将此添加到 SO 以帮助任何像我一样跌跌撞撞的人。