Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4 redirect back with new params

Is it possible to redirect back to the referring url with a new param in the query string?

something like this:

redirect_to :back, custom_param='foo'
like image 275
user1066183 Avatar asked Oct 02 '13 09:10

user1066183


2 Answers

Try this:

# get a URI object for referring url 
referrer_url = URI.parse(request.referrer) rescue URI.parse(some_default_url)
                    # need to have a default in case referrer is not given


# append the query string to the  referrer url
referrer_url.query = Rack::Utils.parse_nested_query(referrer_url.query).
                    # referrer_url.query returns the existing query string => "f=b"
                    # Rack::Utils.parse_nested_query converts query string to hash => {f: "b"}
                    merge({cp: 'foo'}).
                    # merge appends or overwrites the new parameter  => {f: "b", cp: :foo'}
                    to_query
                    # to_query converts hash back to query string => "f=b&cp=foo"



# redirect to the referrer url with the modified query string
redirect_to referrer_url.to_s
                    # to_s converts the URI object to url string
like image 193
tihom Avatar answered Nov 04 '22 10:11

tihom


You can put it in session and then redirect back

session[:somekey] = value
redirect_to :back
like image 6
techvineet Avatar answered Nov 04 '22 10:11

techvineet