4

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?

Ashish Jambhulkar
  • 1,374
  • 2
  • 14
  • 26
dragon
  • 101
  • 4

3 Answers3

12

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.

sa77
  • 3,563
  • 3
  • 24
  • 37
0

As we define the routes in routes.rb, than the control goes to that controller action at that time the controller get's initiated to work

  • I would like to see a lower layer explanation of where, what point and how a controller gets instantiated. – dragon Aug 12 '17 at 07:50
0

It is more related to object oriented programming, The object is always instantiated when you call new on class

2.0.0-p648 :001 > Class.new
 => #<Class:0x007fee8e99d9a8> 
2.0.0-p648 :002 > 

Here the object is instantiated, and similarly in rails when you call any action lets say

def new
  @article = Article.new
end

new object gets initiated, when you click on save, you are actually calling create action, and pass the current object.

def create
  @article = Article.create(article_params)
  @article.save
end

here .create method filled object with article_params and .save method saves object in database.

Ashish Jambhulkar
  • 1,374
  • 2
  • 14
  • 26
  • I understand how a model is getting instantiated but I would like to know how a controller gets instantiated. – dragon Aug 12 '17 at 07:49
  • 1
    When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action. – Ashish Jambhulkar Aug 12 '17 at 08:03