简体   繁体   English

来自Rack中间件的Alter Rails params哈希

[英]Alter Rails params hash from Rack middleware

I am attempting to add a value to the Rails params hash from a custom Rack middleware object. 我试图从自定义Rack中间件对象的Rails参数哈希添加一个值。 My current approach is using 我目前的方法是使用

class PortalResolver

 def initialize(app)
   @app = app
 end

  def call(env)
    begin
      url = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}"
      request = Rack::Request.new(env)
      portal_id = DomainService.domain(url) # DomainService is returning the expected value
      request.params['portal_id'] = portal_id
      status, headers, response = @app.call(env)
      [status, headers, response]
    rescue PortalNotFoundError => e
      [403, {'Content-Type' => 'text/html'}, ['']]
    end
  end
end

I'm currently adding the middleware after ActionDispatch::ParamsParser. 我目前正在ActionDispatch :: ParamsParser之后添加中间件。 The parameters don't show up in the Rails params hash from a controller, but do show up in the request.params hash (within the middleware object defined above.) Any ideas? 这些参数不会出现在来自控制器的Rails params散列中,但会显示在request.params散列中(在上面定义的中间件对象中)。任何想法? Help much appreciated. 非常感谢。

The docs for Rack::Request#params say: Rack::Request#params文档说:

Note that modifications will not be persisted in the env. 请注意,修改不会在env中保留。 Use update_param or delete_param if you want to destructively modify params. 如果要破坏性地修改params,请使用update_paramdelete_param

When you use the line 当你使用该行

request.params['portal_id'] = portal_id

you add the new parameter to the hash created for that instance of Rack::Request, but the env that is passed on to rails isn't modified. 您将新参数添加到为Rack :: Request实例创建的哈希,但不会修改传递给rails的env To make the new value available further down the Rack stack use update_param as the docs suggest: 要在Rack堆栈中进一步使用新值,请使用update_param作为文档建议:

request.update_param('portal_id', portal_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM