【问题标题】:Grape: ActiveModel::ForbiddenAttributesError葡萄:ActiveModel::ForbiddenAttributesError
【发布时间】:2015-10-01 09:53:34
【问题描述】:

调用我的 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 - 我觉得很丑。

这怎么可能?有替代品吗?

【问题讨论】:

    标签: ruby-on-rails strong-parameters grape-api


    【解决方案1】:

    在其他任何地方搜索互联网后,我在official Grape Docs 中找到了解决方案 - 真是一个冠军! /讽刺

    如果您的 Rails 版本是 4.0+ 并且应用程序使用 ActiveRecord 的默认模型层,您将需要使用 hashie-forbidden_attributes gem。此 gem 禁用安全性 模型层的 strong_params 功能,允许您使用 而是 Grape 自己的参数验证。

    我将此添加到 SO 以帮助任何应该像我一样绊倒的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      相关资源
      最近更新 更多