Reputation: 432
Looking to see if there is an elegant solution for adding a parameter to each GET request based upon a session value in a Rails app. (4.2.6 if needed)
Example:
We have a session variable session[:test] = 123
User makes request to example.com/random_path
We'd like the request to always append the param "?test=#{session[:test]}"
So the user would be routed to example.com/random_path?test=123
Love to hear any ideas on this - thanks!
Upvotes: 1
Views: 192
Reputation: 511
The routes can be generated as:
random_path(random, test: session[:test])
It will redirect to:
example.com/random_path?test=123
where test = session[:test]
Upvotes: 0
Reputation: 48525
If you want the generated URLs to that path to always have a certain parameter in them when they are generated, you can write your own url_for
or link_to
helper for that specific route, or override default_url_options
and set this parameter if the action or controller name match some condition:
class ApplicationController < ActionController::Base
def default_url_options(options = {})
if controller_name == 'my_controller'
options[:test] = session[:test]
end
options
end
end
Upvotes: 1
Reputation: 34657
Would redirect_to be a solution? See the code below:
redirected_url = "https://foo.com?test=#{session[:test]}"
redirect_to redirected_url
Hope it helps....
Upvotes: 0