Bird
Raised Fist0
Ruby on Railsframework~10 mins

Why controllers handle requests in Ruby on Rails - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why controllers handle requests
Browser sends HTTP request
↓
Rails router receives request
↓
Router finds matching controller & action
↓
Controller action runs
↓
Controller processes data & prepares response
↓
Controller sends response back to browser
This flow shows how a web request travels from the browser to the Rails controller, which handles it and sends back a response.
Execution Sample
Ruby on Rails
class BooksController < ApplicationController
  def show
    @book = Book.find(params[:id])
    render json: @book
  end
end
This controller action finds a book by ID and sends it back as JSON when a request comes in.
Execution Table
StepActionInput/StateOutput/Result
1Browser sends GET /books/3URL: /books/3Request received by Rails router
2Router matches routeRoute: GET /books/:idCalls BooksController#show with params[:id] = 3
3Controller action startsparams[:id] = 3Finds Book with id=3
4Book foundBook object with id=3Assigns to @book
5Render JSON response@book assignedSends JSON of book data to browser
6Response sentJSON dataBrowser receives book info
7EndRequest handledNo further action
💡 Request handled fully by controller; response sent back to browser
Variable Tracker
VariableStartAfter Step 3After Step 4Final
params[:id]nil333
@booknilnilBook(id=3)Book(id=3)
Key Moments - 3 Insights
Why does the router send the request to the controller?
The router matches the URL pattern to a controller and action, so it knows which controller method should handle the request (see execution_table step 2).
Why does the controller find the book instead of the router?
The controller handles the logic and data fetching to keep routing simple and focused on directing requests (see execution_table step 3 and 4).
What does the controller do after finding the book?
It prepares the response, here rendering the book as JSON, and sends it back to the browser (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of params[:id] at step 3?
A3
Bnil
CBook object
DJSON data
💡 Hint
Check the 'Input/State' column at step 3 in the execution_table.
At which step does the controller send the response back to the browser?
AStep 4
BStep 2
CStep 5
DStep 1
💡 Hint
Look for the step where 'Render JSON response' happens in the execution_table.
If the router did not find a matching route, what would happen?
AThe controller action runs anyway
BThe browser gets a 404 error
CThe book is found by default
DThe router sends a JSON response
💡 Hint
Think about what happens if the router cannot match the URL to any controller (not shown in table but common Rails behavior).
Concept Snapshot
In Rails, controllers handle requests by receiving data from the router.
They run actions to process data and prepare responses.
Controllers keep routing simple and manage app logic.
They send the final response back to the browser.
This separation keeps code organized and clear.
Full Transcript
When a browser sends a request, Rails first uses the router to find which controller and action should handle it. The controller then runs the action method, using parameters from the request to find or process data. After preparing the data, the controller sends a response back to the browser, such as rendering JSON or HTML. This flow keeps routing focused on directing requests, while controllers manage the app's logic and responses.

Practice

(1/5)
1. Why do Rails controllers handle user requests?
easy
A. To decide how the app should respond to user actions
B. To store data permanently in the database
C. To style the web pages with CSS
D. To manage server hardware resources

Solution

  1. Step 1: Understand the role of controllers in Rails

    Controllers receive user requests and decide what the app should do next, such as showing a page or saving data.
  2. Step 2: Differentiate controller responsibilities from other parts

    Storing data is handled by models, styling by CSS, and hardware management is outside Rails scope.
  3. Final Answer:

    To decide how the app should respond to user actions -> Option A
  4. Quick Check:

    Controllers handle requests = A [OK]
Hint: Controllers decide app response to user actions [OK]
Common Mistakes:
  • Confusing controllers with models for data storage
  • Thinking controllers handle styling or hardware
  • Believing controllers directly manage databases
2. Which of the following is the correct way to define an action named show in a Rails controller?
easy
A. function show() { // action code }
B. def show # action code end
C. show => { // action code }
D. action show { // action code }

Solution

  1. Step 1: Recall Ruby method syntax in Rails controllers

    Rails controller actions are Ruby methods defined with def action_name and end.
  2. Step 2: Identify correct syntax among options

    def show # action code end uses Ruby method syntax; others use JavaScript or invalid syntax.
  3. Final Answer:

    def show\n # action code\nend -> Option B
  4. Quick Check:

    Ruby method syntax = A [OK]
Hint: Rails actions are Ruby methods using def/end [OK]
Common Mistakes:
  • Using JavaScript function syntax in Rails controllers
  • Trying to define actions with arrow functions
  • Using invalid keywords like 'action'
3. Given this controller code, what will be the rendered output when visiting /welcome/greet?
class WelcomeController < ApplicationController
  def greet
    @message = "Hello, Rails!"
  end
end
Assuming the view greet.html.erb contains:
<h1><%= @message %></h1>
medium
A. Hello, Rails!
B. <%= @message %>
C.

Hello, Rails!

D. Error: undefined variable

Solution

  1. Step 1: Understand controller sets instance variable

    The controller action greet sets @message to "Hello, Rails!" which is accessible in the view.
  2. Step 2: View renders the instance variable inside <h1> tags

    The view uses ERB syntax <%= @message %> to insert the message text inside an <h1> element.
  3. Final Answer:

    <h1>Hello, Rails!</h1> -> Option C
  4. Quick Check:

    Instance variable rendered in view = B [OK]
Hint: Instance variables in controller appear in views with <%= %> [OK]
Common Mistakes:
  • Expecting raw variable name instead of its value
  • Confusing plain text with HTML tags
  • Assuming variable is undefined without @
4. Identify the error in this controller code snippet:
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def create
    product = Product.new(params[:product])
    if product.save
      redirect_to product_path(product)
    else
      render :new
    end
  end
end
medium
A. Using params[:product] directly without strong parameters
B. Missing return statement in create action
C. No instance variable @product in create action
D. Incorrect inheritance from ApplicationController

Solution

  1. Step 1: Review how parameters are handled in create action

    The code uses params[:product] directly, which is unsafe and disallowed in modern Rails without strong parameters.
  2. Step 2: Identify missing strong parameters usage

    Rails requires filtering params with methods like product_params to permit only allowed attributes.
  3. Final Answer:

    Using params[:product] directly without strong parameters -> Option A
  4. Quick Check:

    Strong parameters required = D [OK]
Hint: Always use strong parameters to permit attributes [OK]
Common Mistakes:
  • Ignoring strong parameters and using raw params
  • Thinking return statements are needed in Rails actions
  • Confusing instance variables with local variables
5. You want a controller action to handle both showing a form and processing form data for creating a new user. Which approach best follows Rails controller patterns?
hard
A. Use one action create to show form and save user
B. Use one action new to both show form and save user
C. Handle form display and data processing in the view file
D. Use separate actions: new to show form, create to process data

Solution

  1. Step 1: Understand Rails RESTful controller conventions

    Rails uses separate actions: new to display the form, and create to handle form submission and save data.
  2. Step 2: Evaluate options against best practices

    Combining form display and data processing in one action or view breaks separation of concerns and Rails conventions.
  3. Final Answer:

    Use separate actions: new to show form, create to process data -> Option D
  4. Quick Check:

    Separate new and create actions = C [OK]
Hint: Use new for form, create for saving data [OK]
Common Mistakes:
  • Combining form display and processing in one action
  • Trying to handle logic inside views
  • Ignoring Rails RESTful conventions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard