Rails redirect_to with params

33,289

Solution 1

If you don't have a named route for /hello then you'll have to hardcode the params into the string that you pass to redirect_to.

But if you had something like hello_path then you could use redirect_to hello_path(:param1 => 1, :param2 => 2)

Solution 2

Instead of:

 redirect_to some_params

You can do:

 redirect_to url_for(some_params)

You're turning the params into a url with url_for before passing it to redirect_to, so what you pass redirect_to ends up being a URL as a string, which redirect_to is happy to redirect to.

Note well: I don't understand why redirect_to refuses to use params. It used to be willing to use params. At some points someone added something to Rails to forbid it. It makes me suspect that there are security reasons for doing so, and if so, these security reasons could mean that manually doing redirect_to url_for(p) has security implications too. But I haven't yet been able to find any documentation explaining what's up here.

update: I've found the security warning, but haven't digested it yet: https://github.com/rails/rails/pull/16170

Solution 3

The easiest way (if it's not a named route) will be:

redirect_to "/hello?#{hash.to_param}"

See: http://apidock.com/rails/Hash/to_param

Share:
33,289
ygnhzeus
Author by

ygnhzeus

Updated on February 11, 2020

Comments

  • ygnhzeus
    ygnhzeus over 4 years

    I want to pass parameters (a hash) to redirect_to, how to do this? For example:

    hash = { :parm1 => "hi", :parm2 => "hi" }
    

    and I want to redirect to page /hello

    URL like this: /hello?parm1=hi&parm2=hi