我试图从自定义Rack中间件对象的Rails参数哈希值中添加一个值.我目前的方法是使用
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,response] rescue PortalNotFoundError => e [403,{'Content-Type' => 'text/html'},['']] end end end
我目前正在ActionDispatch :: ParamsParser之后添加中间件.参数不会出现在来自控制器的Rails params散列中,但会显示在request.params散列中(在上面定义的中间件对象中).任何想法?非常感谢.
解决方法
docs for
Rack::Request#params
说:
Note that modifications will not be persisted in the env. Use 07001 or 07002 if you want to destructively modify params.
当你使用该行
request.params['portal_id'] = portal_id
您将新参数添加到为Rack :: Request实例创建的哈希中,但不会修改传递给rails的env.要在Rack堆栈中进一步使用新值,请使用update_param作为文档建议:
request.update_param('portal_id',portal_id)