What Is MVC? How Rails Splits Model, View and Controller
Follow one request and you can tell where each piece of code belongs
Anyone can recite "Model is data, View is display, Controller is the middleman." The trouble starts right after that. Where does this code go? Why is this SQL running here? Following one real request answers both.
The path of GET /posts/1
config/routes.rb hands the URL to posts#show, PostsController#show runs, and show.html.erb builds the HTML. You don't need to call render; Rails draws the template named after the action.
@post is visible in the view because Rails copies instance variables over. Local variables don't make the trip.
The textbook order isn't the real order
The usual picture is "Controller → Model (DB query) → View." Log it on Rails 8.0.4 and the order is different.
def index
@posts = Post.where(id: 1) # no SQL yet
end
controller starts
controller ends (query object built)
view starts
SQL SELECT "posts".* FROM "posts" WHERE ...
view ends
where returns an object holding the conditions. The SQL runs when the view first reads it. So time logged under the view doesn't always mean a slow view, and an N+1 fires inside the view's each, not in the controller.
Where does this code go?
Rules that stay inside one model (validations, derived state) go in the model. Pulling values from the request and choosing a response is the controller's job. How it looks belongs in the view.
Work that touches several models or calls an external API is the awkward case. It starts in the controller until one action runs to dozens of lines (Fat Controller). Move it to the model and now the model is thousands of lines (Fat Model). Either way, testing it means running a request or a callback too.
Plain MVC or a service object?
If a screen just saves and reads one model, a service only adds a file. The test is simple: wrapping several models in one transaction, calling an external API, or running the same procedure from two places. That's when it moves to app/services, and this repo splits things the same way. Skip classes that are services in name only and just delegate to one method.
If you're staring at a bloated Rails controller and don't know where to start splitting, you can ask negabaro.
Architecture Diagram
GET /posts/1
config/routes.rb
Key Points
Read the order of `Processing by`, SQL and `Rendered` in your log
Use `bin/rails routes` to see which action a URL reaches
When an action grows, move single-model rules to the model first
Extract a service once you have several models, an external API or reuse