[Ruby] [Rails] Get UserAgent with controller

less than 1 minute read

What is UserAgent?

UserAgent is the information about the WEB usage environment included in the HTTP request header. It includes information such as browser type, browser version, and terminal OS type.

What is an HTTP request header?

The HTTP request header is additional information sent with the request information sent from the browser to the website when the website is accessed. Information such as UserAgent, Referer (link source URL), and Authorization (authentication information).

How to get UserAgent in Rails

Rails controller has accessor method that points to request object, By using it, you can easily get the UserAgent in the controller as follows.

request.user_agent

request object that can be acquired in various ways other than UserAgent

You can easily get the request information as follows using the request object.

request.url # The entire URL used in the request
request.remote_ip # client IP address
request.query_string # URL query string


(reference) [Rails Guide: request object and response object](https://railsguides.jp/action_controller_overview.html#request%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%A8response%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83(%88)