0
0
Ruby on Railsframework~5 mins

belongs_to relationship in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIn the model declaring <code>belongs_to</code>
BIn the model declaring <code>has_many</code>
CIn a join table
DIn the database schema only
What does belongs_to :user mean inside a model?
AThis model has many users
BThis model is unrelated to users
CThis model belongs to one user
DThis model owns the user model
How do you make a belongs_to association optional?
AAdd <code>optional: true</code> to the association
BAdd <code>required: false</code> to the association
CRemove the foreign key column
DUse <code>has_one</code> instead
If a model belongs_to :post, what foreign key column is expected?
A<code>post_key</code>
B<code>post_id</code>
C<code>post_fk</code>
D<code>postRef</code>
What validation does Rails add by default to belongs_to associations?
ANo validation by default
BUniqueness validation
CLength validation
DPresence validation of the associated object
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.