Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing param values to redirect_to as querystring in rails

This should be simple, but I can't seem to find an easy answer.

How can I pass param values from the current request into a redirect_to call? I have some form values I'd like to pass into the query string of a GET redirect

I'd like to do something like:

redirect_to @thing, :foo => params[:foo]

and get sent to:

http://things/4?[foo][key1]=val1&[foo][key2]=val2

Thanks!

Also - how could this be handled for a redirect_to :back?

redirect_to :back, :foo => params[:foo]
like image 711
Justin Avatar asked Apr 03 '09 18:04

Justin


People also ask

How do you pass a value in Querystring?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

How do I redirect in rails?

Rails's redirect_to takes two parameters, option and response_status (optional). It redirects the browser to the target specified in options. This parameter can be: Hash - The URL will be generated by calling url_for with the options.


2 Answers

The 'Record' form of redirect_to uses the second argument only for the response status. You'll have to use another form of redirect_to, like the 'String' form. e.g.:

redirect_to thing_path(@thing, :foo => params[:foo])

which will work for nested params[:foo] params like you mentioned. Or, as Drew commented below, you can use polymorphic_url (or _path):

redirect_to polymorphic_path(@thing, :foo => params[:foo])
like image 90
Jordan Brough Avatar answered Oct 13 '22 15:10

Jordan Brough


To add to Jordan's answer:

If you don't know what type of object @thing might be, you can use the universal polymorphic_url method. This is the method that is called internally when you pass in an object to redirect_to anyway.

like image 40
Drew Blas Avatar answered Oct 13 '22 15:10

Drew Blas