Ruby on Rails Ruby on Rails MVC Architecture & Routing 2 — Questions and Answers
Question 1: In Rails routing, what does `root 'pages#home'` specify?
- The admin root path
- The URL for the home controller
- The default route for the application's root URL '/' (Correct answer)
- A named route called 'root'
Correct answer: The default route for the application's root URL '/'
`root 'pages#home'` maps the root URL (/) to the `home` action in the `PagesController`.
Question 2: How do you create a named route helper in Rails that generates a URL like `/about`?
- get '/about', to: 'pages#about', as: 'about' (Correct answer)
- route '/about' => 'pages#about'
- map '/about' to: 'pages#about'
- path :about => 'pages#about'
Correct answer: get '/about', to: 'pages#about', as: 'about'
The `as:` option in a route definition creates a named route helper (e.g., `about_path` and `about_url`).
Question 3: What Rails convention determines which view template is rendered by default when no explicit `render` call is made?
- The view matching the controller name and action name (Correct answer)
- The index view of the current controller
- The application layout
- The view specified in routes.rb
Correct answer: The view matching the controller name and action name
Rails implicitly renders app/views/<controller_name>/<action_name>.html.erb when no explicit render is called.
Question 4: Which HTTP verb does Rails use for the `update` action in a RESTful resource by default?
- POST
- PUT or PATCH (Correct answer)
- GET
- DELETE
Correct answer: PUT or PATCH
Rails maps the `update` action to both PATCH (preferred) and PUT HTTP verbs for RESTful resource routes.
Question 5: What is the role of the View layer in Rails MVC?
- Querying the database
- Processing business logic
- Presenting data to the user as HTML or other formats (Correct answer)
- Handling HTTP request routing
Correct answer: Presenting data to the user as HTML or other formats
The View is responsible for presenting model data to the user, typically as HTML using ERB or other template engines.
Question 6: Which Rails command displays all defined routes for an application?
- rails show:routes
- rails routes (Correct answer)
- rake routes:list
- rails routes:display
Correct answer: rails routes
`rails routes` (or `rake routes` in older versions) prints all URL patterns, HTTP verbs, and controller#action mappings.
In Rails routing, what does `root 'pages#home'` specify?