Ruby/Rails - Open a URL From The Controller In New Window

This is not possible to do directly from the controller. Using redirect_to @url has the effect of opening an URL in the same "window", as it simply sends a HTTP redirect instruction back to the browser. redirect_to is not capable of opening new windows. The controller resides on the server side, and opening a new window belongs to the client side.

Some options:

a) render a link with <%= link_to 'Google', 'google.com', :target => '_blank' %> or <a href="google.com" target="_blank">Google</a> which the user can click on in a new view

b) use JavaScript to open the link automatically, but beware that browsers may treat this as a popup and block it

By combining these options you can open links in new window for browsers/users who allow it, and fall back to a regular URL in case that didn't work.


You can't do that in rails, because your script is being executed on a server. Use Javascript to work with browser on the client side.


Well, it's not that you CAN'T do it, it's just kind of a convoluted process. I did this in a project I'm working on. Basically, it's a mixture of Rails goodness and Javascript. I simply passed a flash notice on creation of an instance, and then used a script to set that flash notice equal to a js variable, and a redirect_url. If that particular flash notice pops up on that page, it redirects in the js script. Like I said, it's hack hack hack, but it works for my purposes.


As the others point out, you can't (and shouldn't) do this in the controller. In the view you can use

<%= link_to @url, :target => "_blank" %>