Ruby on Rails Ruby on Rails MVC Architecture & Routing 1 — Questions and Answers
Question 1: In Rails MVC, which layer is responsible for handling HTTP requests and coordinating between the Model and View?
- Model
- View
- Controller (Correct answer)
- Router
Correct answer: Controller
The Controller receives HTTP requests, interacts with the Model for data, and passes that data to the View for rendering.
Question 2: Which Rails file defines the mapping between URLs and controller actions?
- application.rb
- routes.rb (Correct answer)
- schema.rb
- config.rb
Correct answer: routes.rb
config/routes.rb is where you define URL patterns and their corresponding controller#action mappings.
Question 3: What does the Rails helper `resources :articles` generate in routes.rb?
- Only GET routes for articles
- Only CRUD routes for index and show
- Seven RESTful routes for the articles resource (Correct answer)
- A single named route for articles
Correct answer: Seven RESTful routes for the articles resource
`resources :articles` generates all seven standard RESTful routes: index, show, new, create, edit, update, and destroy.
Question 4: In Rails, where do you place shared application layout files that wrap all views?
- app/views/shared/
- app/layouts/
- app/views/layouts/ (Correct answer)
- app/templates/
Correct answer: app/views/layouts/
Application layout files (e.g., application.html.erb) are stored in app/views/layouts/ and wrap the rendered view content.
Question 5: Which method in a Rails controller renders a specific view template explicitly?
- show
- display
- render (Correct answer)
- present
Correct answer: render
The `render` method explicitly specifies which template to render, overriding Rails' default convention-based rendering.
Question 6: What is the purpose of `before_action` in a Rails controller?
- To define a route before an action
- To run a method before specified controller actions execute (Correct answer)
- To validate model data before saving
- To preload assets before rendering
Correct answer: To run a method before specified controller actions execute
`before_action` registers a callback that runs before one or more controller actions, commonly used for authentication.
In Rails MVC, which layer is responsible for handling HTTP requests and coordinating between the Model and View?