我在执行某个操作时尝试打开一个页面。所以在我的 Controller 中我有以下内容:
class Controller < ApplicationController
require 'open-uri'
def action
open("http://www.google.com") #if i use this, it just goes to my action page
open("www.google.com") #if i use this, it gives the error
end
end
错误:
Errno::ENOENT in Controller#action
No such file or directory - www.google.com
我发现的所有解决方案都说需要“open-uri”,我相信我做到了。我在这里做错了什么?
编辑:
抱歉,我应该说得更清楚。我可能必须在新选项卡中打开多个页面,这就是为什么我决定使用 open 而不是 redirect_to。例如:
class Controller < ApplicationController
require 'open-uri'
def action
open("http://www.google.com")
open("http://www.yahoo.com")
end
end
这样做会同时打开 google.com 和 yahoo.com。
最佳答案
open
通常用于让您的服务器访问外部站点(并可能解析响应)。它不允许您重定向您的用户。为了与客户端交互,您需要使用 View + javascript。
<%= link_to @url, target: "_blank" %>
对于您想要的每个页面,然后通过 JavaScript 自动单击它们。
有关更多信息,请参阅:How do I programmatically click a link with javascript?
如果用户没有启用 JS,则显示链接作为后备。另请参阅这个问题:Ruby/Rails - Open a URL From The Controller In New Window
关于ruby-on-rails - 打开 ("url or file name")并要求 'open-uri' 无法在 Rails 上运行 ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17687776/