使用redirect_to并传递额外参数

3
我正在尝试返回 redirect_to 并传递额外参数。这是我在控制器中的代码:
redirect_to(env['omniauth.origin'], :hello => "hello world")

这个重定向URL是正确的,但是"hello"没有被传递。有什么想法吗?

你的目标(OmniAuth)是外部URL吗? - Deradon
4个回答

5

env['omniauth.origin']是一个字符串吗?如果是的话,我认为这种方法行不通。您可以尝试按以下方式添加参数:

redirect_to(env['omniauth.origin'] + "?hello=helloworld")

或类似的东西。

4

redirect_to 最终会调用 url_for,如果传递给 url_for 的参数是字符串,则直接返回该字符串。它会忽略其他任何选项。

我建议使用 Rails 的 Hash#to_query 方法:

redirect_to([env['omniauth.origin'], '?', params.to_query].join)

1
我应该注意,只有在env['omniauth.origin']不包含查询字符串时,它才会生成有效的URL。 - Brandan

1
在你的路由中添加一个路径,并将“helloworld”作为参数传递。
redirect_to(route_in_file_path('helloworld'))

0
ApplicationController类中添加一个函数。
class ApplicationController  < ActionController::Base    
  def update_uri(url, opt={})
    URI(url).tap do |u|
      u.query = [u.query, opt.map{ |k, v| "#{k}=#{URI.encode(v)}" }].
                 compact.join("&")
    end
  end
  helper_method :update_uri # expose the controller method as helper
end

现在你可以做以下事情:

redirect_to update_uri(env['omniauth.origin'], :hello => "Hello World")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接