Back to Course

Reading the Source · Card 1

What belongs_to :user actually adds to your model

One short line. Behind it: a handful of methods on the model, some extra info Rails stores about the class, a validation, and a little dirty-tracking. Knowing what shows up changes how you read every Rails model.

The familiar line

You've written this dozens of times. What does it actually generate?

class Post < ApplicationRecord
  belongs_to :user
end

What's visible at the API surface

A Post is now connected to a User. You can call post.user and assign with post.user = some_user, and most developers stop there. Everything else Rails wires up from that one line stays invisible: builder methods, dirty-tracking helpers, a reflection on the class, a presence validation. When a method appears in someone else's model and isn't defined anywhere in the file, it almost always came from a declaration like this one.

Take a moment. Without peeking at docs or a Rails console, name every method belongs_to :user adds to a Post. Most people get to two. There are actually about eight on the instance, plus a few more things on the class.