Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - redirect_to(url, :myparam => 'abc')

I can't work this out.

url = "www.mysite.com/?param1=abc"

redirect_to(url, :param2 => 'xyz')

### Should this go to - www.mysite.com/?param1=abc&param2=xyz

Or am I missing something? It doesn't seem to work?

like image 515
Alex Fox Avatar asked Dec 04 '22 02:12

Alex Fox


2 Answers

From the documentation:

redirect_to(options = {}, response_status = {})

Redirects the browser to the target specified in options. This parameter can take one of three forms:

Hash - The URL will be generated by calling url_for with the options.

Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record.

String starting with protocol:// (like http://) or a protocol relative reference (like //) - Is passed straight through as the target for redirection.

You're passing a String as the first argument, so it's using the 3rd option. Your second parameter is interpreted as the value for the response_status parameter.

So, if your redirect is an internal one (to the same app), you don't need to specify the scheme and hostname. Just use

redirect_to root_url(param1 => 'abc', param2 => 'xyz')

If it's an external URL, build the complete URL before redirecting:

url = "www.mysite.com/?param1=abc&params2=xyz"
redirect_to url
like image 129
Thilo Avatar answered Dec 05 '22 16:12

Thilo


redirect_to is not a Ruby function but is commonly used in Ruby on Rails. You can find its documentation with a lot of working examples here.

If you want to open a website within plain Ruby, use the 'open-uri' class. You can find its documentation here.

I hope this helps understanding why redirect_to doesn't work in plain Ruby and might help using it with and without Rails.

like image 36
Jeehut Avatar answered Dec 05 '22 15:12

Jeehut