What's the difference between belongs_to and has_one?

Viewed 72412

What is the difference between a belongs_to and a has_one?

Reading the Ruby on Rails guide hasn't helped me.

6 Answers

has_one

  • This method should only be used if the other class contains the foreign key.

belongs_to

  • This method should only be used if the current class contains the foreign key.

From a simplicity standpoint, belongs_to is better than has_one because in has_one, you would have to add the following constraints to the model and table that has the foreign key to enforce the has_one relationship:

  • validates :foreign_key, presence: true, uniqueness: true
  • add a database unique index on the foreign key.
Related