In Rails, how do I access the Request.ServerVariables like you do in ASP?
-
21-08-2019 - |
Question
I want to access a given Requests ServerVariables, but I can't seem to find anything on Google on how to get access to the Server Vars of the request object. How do I do this or am I doomed to simply never know?
An example of why I'd want to do this (but not actually what I want to do):
User logs in, and you want to store the IP address of place where they logged in, or perhaps I want to record the user-agent or referer from the browser that they are viewing the site.
Solution
You should look at the request
object that's available from the controller. There are a bunch of methods like
request.remote_ip
you can read more about the Request object on the Rails API site
OTHER TIPS
The request
accessor in a controller returns an ActionDispatch::Request object which can access all of the server variables you would expect.
Best documentation I've found for it is here: http://apidock.com/rails/v3.2.1/ActionDispatch/Request
Sometimes you have methods like request.remote_ip
as mentioned in the other answer, other times you can access things via request.env
, for example, to get the user agent, use request.env["HTTP_USER_AGENT"]