加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 来自Rack中间件的Alter Rails params hash

发布时间:2020-12-16 19:16:15 所属栏目:百科 来源:网络整理
导读:我试图从自定义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(en
我试图从自定义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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读