gpt4 book ai didi

ruby-on-rails - 葡萄和 ActiveRecord 的 ForbiddenAttributesError

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:01 24 4
gpt4 key购买 nike

我有一个使用 Grape 的 ruby​​ 应用程序,但它没有 Rails。

class Article < ActiveRecord::Base
end

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

Article.create 给出 ActiveModel::ForbiddenAttributesError:

有一些关于它的讨论 here , 但我不明白它。我试过这个建议:

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

这次 @permitted_pa​​rams 是空的,所以属性没有了。

我也尝试过用 ActionController::Parameters 包装哈希值,但由于其他错误而失败。

目前在 Grape 中解决 ForbiddenAttributesError 的建议解决方案是什么?

Grape 使用 hashie gem 作为 params,和 their solution因为这包括一个名为 hashie_rails 的 gem,但是这个 gem 带来了所有的 rails ,但我不想要任何一个。所以我需要一个普通的解决方案。

最佳答案

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

gem 文件

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

关于ruby-on-rails - 葡萄和 ActiveRecord 的 ForbiddenAttributesError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com