3

将应用程序从 Rails 4.2.9 迁移到 5.2.1。

这是最新一期:

$ rails console
/Users/meltemi/rails/myapp/config/initializers/disable_xml_params.rb:3:in `<top (required)>': uninitialized constant ActionDispatch::ParamsParser (NameError)
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/railties-5.2.1/lib/rails/engine.rb:657:in `block in load_config_initializer'
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/notifications.rb:170:in `instrument'
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/railties-5.2.1/lib/rails/engine.rb:656:in `load_config_initializer'

初始化程序中有问题的代码行:

# config/initializers/disable_xml_params.rb
ActionDispatch::ParamsParser::DEFAULT_PARSERS.delete(Mime::XML)

导轨指南说:

ActionDispatch::ParamsParser 已弃用,并已从中间件堆栈中删除。要配置参数解析器,请使用 ActionDispatch::Request.parameter_parsers=。(提交,提交)

所以我尝试了以下方法:

ActionDispatch::Request.parameter_parsers.delete(Mime::XML)

但这会引发更多错误:

$ rails console
/Users/meltemi/rails/myapp/config/initializers/disable_xml_params.rb:3:in `<top (required)>': uninitialized constant Mime::XML (NameError)
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/railties-5.2.1/lib/rails/engine.rb:657:in `block in load_config_initializer'
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/notifications.rb:170:in `instrument'
    from /Users/meltemi/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/railties-5.2.1/lib/rails/engine.rb:656:in `load_config_initializer'

有没有更好的方法在该对象上调用 .delete ?

4

1 回答 1

3

您必须从中获取现有值parameter_parsers,对其进行修改以满足您的需要,然后将值重置为修改后的值。来自ActionDispatch::Http::Parameters 文档

parameter_parsers=(parsers)

为给定的 MIME 类型配置参数解析器。

它接受一个散列,其中键是 MIME 类型的符号,值是 proc。

original_parsers = ActionDispatch::Request.parameter_parsers
xml_parser = -> (raw_post) { Hash.from_xml(raw_post) || {} }
new_parsers = original_parsers.merge(xml: xml_parser)
ActionDispatch::Request.parameter_parsers = new_parsers

在您的特定情况下,您应该查看解析器original_parsers以查看是否有任何要删除的内容。在我方便查看的简单 Rails 5 应用程序中,我拥有的唯一值是:

=> {
    :json => #<Proc:0x00007fe818fc6fb8@/Users/foo/.rvm/gems/ruby-2.6.0-preview2/gems/actionpack-5.2.1/lib/action_dispatch/http/parameters.rb:11 (lambda)>
}

您的应用程序的配置可能有所不同,但要回答有关如何删除值的问题,这个简单的版本应该可以工作:

ActionDispatch::Request.parameter_parsers = ActionDispatch::Request.parameter_parsers.except(:json)

您可以在此答案中找到其他有用的信息。

于 2018-10-29T23:10:51.763 回答