18

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'
tihom
  • 7,923
  • 1
  • 25
  • 29
user1066183
  • 2,444
  • 4
  • 28
  • 57

3 Answers3

8

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
tihom
  • 7,923
  • 1
  • 25
  • 29
  • One gotcha here. `Rack::Utils.parse_nested_query(referrer_url.query)` returns a hash with stringified keys. So if your `referrer_url` has `cp=bar` as its current query string. The query of the url will be: `cp=bar&cp=foo`. Change `Rack::Utils.parse_nested_query(referrer_url.query)` to `Rack::Utils.parse_nested_query(referrer_url.query).symbolize_keys.` or `Rack::Utils.parse_nested_query(referrer_url.query).stringify_keys` as needed – DickieBoy Apr 23 '15 at 13:38
6

You can put it in session and then redirect back

session[:somekey] = value
redirect_to :back
techvineet
  • 5,041
  • 2
  • 30
  • 28
3

Another approach could be to pass it via "flash" (it goes away automatically after the redirect request):

flash[:somekey] = 'some value'
redirect_to :back

However, as one of my colleagues noted, a better way is probably to return it as a query param, to keep it stateless and distinguish the two URLs. It seems there isn't a nice, built-in Rails way to do that, which makes me wonder what else is wrong with this approach.

dzajic
  • 3,062
  • 2
  • 15
  • 9