Back to Course

Practice · Reading the Source · Card 1

What does optional: true actually change?

One option flag separates these two models. The visible difference is "must have a user vs not." The mechanism behind it is more specific than that.

The code

Same association. Different behavior. What did Rails wire up differently?

class Post < ApplicationRecord
  belongs_to :user
end

class Comment < ApplicationRecord
  belongs_to :user, optional: true
end

The question

A Post with no user can't save. A Comment with no user saves fine. Which of these is the actual mechanism behind that difference?

Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.