💎 Ruby on Rails
Beginner
What is the difference between belongs_to and has_one?
Answer
Both define a one-to-one relationship, but from different sides. belongs_to declares that the current model holds the foreign key — e.g., Profile belongs_to :user means the profiles table has a user_id column. In Rails 5+, belongs_to requires the associated record to exist by default. has_one declares that the other model holds the foreign key — e.g., User has_one :profile means Rails looks for user_id in the profiles table. The rule of thumb: the model with belongs_to holds the foreign key column.