How Many Types Of Associations Relationships Does A Model Have?

Technology CommunityCategory: Ruby on RailsHow Many Types Of Associations Relationships Does A Model Have?
VietMX Staff asked 3 years ago

When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations:

  • one-to-one: A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.
  • one-to-many: A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.
  • many-to-many: A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.

You indicate these associations by adding declarations to your models:

  • has_one,
  • has_many,
  • belongs_to,
  • has_and_belongs_to_many