Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point does a controller class instantiate a controller object in a Rails web app?

Learning Rails, the point at which a controller gets instantiated is unclear to me whereas, the point at which a model gets instantiated is somewhat recognizable as for example, when a user enters data in a from and clicks the submit button is sort of a trigger that leads to a creation of an object model.

Done some research and I'm visualizing in my head that when a HTTP request is sent via the browser, the routing to a controller becomes the trigger to instantiate a certain controller object from a controller class.

Is this somewhat correct?

like image 282
dragon Avatar asked Dec 13 '22 21:12

dragon


1 Answers

When the HTTP request enters your application server (puma, webrick, etc), the request passes through a stack of middleware (defined in rails gem), which converts the HTTP request into an instance of ActionDispatch::Request class which is used to determine the correct route to dispatch to appropriate controller class in your rails app based on the route definitions defined in config/routes.rb.

The generated request object is then dispatched to the corresponding controller and action method which instantiates the Controller class and invokes an action method on it's instance with an argument of params object (instance of ActionController::Parameters).

This is just a general overview of how Controllers are instantiated. The request object passes through a series of middleware classes and modules before a request object is generated.

Here's a good article if you want to read it in detail.

like image 55
sa77 Avatar answered Apr 08 '23 12:04

sa77