【问题标题】:How to achieve strong parameter protection without Rails?如何在没有 Rails 的情况下实现强大的参数保护?
【发布时间】:2015-05-19 09:22:47
【问题描述】:

我正在使用 Goliath + Grape + Active Record 4.2 + Active Record Migrations 开发样板 Web 应用程序。这是我的迁移文件

# db/migrate/20150519063210_create_albums.rb
class CreateAlbums < ActiveRecord::Migration
  def change
    create_table :albums do |t|
      t.string :name
      t.string :artist
      t.string :genre
      t.date :published_at
    end
  end
end

还有我的模特

# app/models/Album
class Album < ActiveRecord::Base
end

还有 Grape API

class ApiV1 < Grape::API
  version 'v1', using: :path
  format :json

  resource 'albums' do
    get '/' do
      Album.all
    end

    post '/' do
      Album.create(params[:album])  # <-- raises ActiveModel::ForbiddenAttributesError
    end
  end
end

当我使用一些参数调用POST /v1/albums/ 时,应用程序总是引发ActiveModel::ForbiddenAttributesError。似乎 ActiveRecord 想要 ActionController::Parameters 作为参数,但 Grape 给了它 Hashie::Mash

我尝试实现一个简单的 Rack 中间件将 env['params']Hash 转换为 ActionController::Parameters 并在 Goliath::Rack::Params 之后使用它,但 Grape 只是在调用辅助方法 params 时将其清理掉.我还尝试实现和使用 Grape 中间件来做同样的事情并得到同样的结果。

是否有任何解决方案,或者我只需要降级到 ActiveRecord 3?

【问题讨论】:

    标签: ruby activerecord strong-parameters grape-api goliath


    【解决方案1】:

    您可以创建一个助手来使用您的参数生成ActionController::Parameters 的实例:

    require 'action_controller/metal/strong_parameters' 
    
    class ApiV1 < Grape::API
      version 'v1', using: :path
      format :json
    
      helpers do
        def albums_params
          ActionController::Parameters.new(params).require(:album).permit(:attr1, :attr2)
        end
      end
    
      resource 'albums' do
        get '/' do
          Album.all
        end
    
        post '/' do
          Album.create(albums_params)
        end
      end
    end
    

    或者您可以使用hashie-forbidden_attributes gem。

    【讨论】:

    • .update 不工作。你能告诉我它是如何工作的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2021-09-20
    • 2016-02-29
    • 2013-04-21
    相关资源
    最近更新 更多