Recall & Review
beginner
What does the
belongs_to association represent in Rails?It represents a connection where a model holds a reference to another model, meaning each instance belongs to one instance of another model.
Click to reveal answer
beginner
In a
belongs_to relationship, where is the foreign key stored?The foreign key is stored in the model that declares
belongs_to. This key points to the associated model's primary key.Click to reveal answer
beginner
How do you declare a
belongs_to association in a Rails model?Inside the model class, write
belongs_to :other_model_name to set up the association.Click to reveal answer
intermediate
What happens if you try to save a model with a
belongs_to association but the foreign key is missing?By default, Rails will raise a validation error because
belongs_to requires the associated object to be present unless specified otherwise.Click to reveal answer
intermediate
Can a
belongs_to association be optional in Rails? How?Yes, by adding
optional: true to the belongs_to declaration, the association can be saved without the foreign key.Click to reveal answer
Where is the foreign key stored in a
belongs_to association?✗ Incorrect
The foreign key is stored in the model that declares
belongs_to, linking it to the associated model.What does
belongs_to :user mean inside a model?✗ Incorrect
It means each instance of this model is linked to one user instance.
How do you make a
belongs_to association optional?✗ Incorrect
Adding
optional: true allows saving the model without the associated record.If a model
belongs_to :post, what foreign key column is expected?✗ Incorrect
Rails expects the foreign key column named
post_id by convention.What validation does Rails add by default to
belongs_to associations?✗ Incorrect
Rails requires the associated object to be present unless
optional: true is set.Explain how the
belongs_to association works in Rails and where the foreign key is stored.Think about which model 'owns' the reference.
You got /3 concepts.
Describe how to make a
belongs_to association optional and why you might want to do that.Consider cases where the related object might not exist yet.
You got /3 concepts.