1

我正在使用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

还有葡萄 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']从 a转换Hash为 aActionController::Parameters并在之后使用它Goliath::Rack::Params,但是 Grape 只是在调用辅助方法时对其进行清理params。我还尝试实现和使用 Grape 中间件来做同样的事情并得到相同的结果。

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

4

1 回答 1

0

您可以创建一个助手来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。

于 2015-05-19T12:05:30.910 回答