An is a connection between two . It makes much to perform various operations on the records in your code. We will divide associations into four categories: association Active Record models easier One to One One to Many Many to Many Polymorphic One to Many If you are new to Ruby on Rails, be sure to get up your ready and check how to in Rails. rails project create models One to One When you set up relations you are saying that a record contains exactly one instance of another model. For example, if each user in your application has only one profile, you can describe your models as: one-to-one has_one belongs_to < ApplicationRecord < ApplicationRecord class User class Profile :profile :user end end One of the models in the given relation will have method invocation and another one will have . It is used to describe which model contains reference to the other one, in our case, it is the profiles model. has_one belongs_to a foreign key Cover your associations with to make sure everything works the way you want it to. RSpec tests One to Many A association is the most common used relation. This association indicates that each instance of the model A can have instances of another model B and model B belongs to model A. one-to-many zero or more only one Let's check it out via example. We want to create an application where users can write multiple stories, our models should look like this: has_many belongs_to < ApplicationRecord < ApplicationRecord class User class Story :stories :user end end Here, deciding which model will have and which will have is more important than in relations, because it changes the logic of your application. In both cases, the second model contains one reference to the first model in form of a . has_many belongs_to one-to-one foreign key The second model doesn't know about the first model relation to it - it is not aware if the first model has a reference to more than one of them or just to one. The tests for associations get more complex to write the more relations you create. You should check it out how to create your own to make your testing life easier. association factories Many to Many associations are a bit more complex and can be handled in two ways, and relations. Many-to-many "has and belongs to many" "has many through" Has and Belongs to Many A association creates a direct connection with another model. It is simpler than the other one, as it only requires calling from both models. has_and_belongs_to_many many-to-many has_and_belongs_to_many : Let's say, a user can have many different roles and the same role may contain many users, our models would be like this: Example has_and_belongs_to_many has_and_belongs_to_many < ApplicationRecord < ApplicationRecord class User class Role :roles :users end end You will need to create a for this association to work. It is a table that connects two different models. The join table is created with rails function in a separate . join table create_join_table :user, :role migration create_table , t.references , , t.references , , < ActiveRecord::Migration class CreateUserRoles def change :user_roles id: false do |t| :user index: true foreign_key: true :role index: true foreign_key: true end end end This is a very simple approach, but you don't have the direct access to related objects, you can only hold references to two models and nothing else. Has Many Through Another way to define a association is to use the association type. Here we define a , to handle that connection between two different ones. many-to-many has many through separate model Instead of putting down a new example, you should check ! It explains everything you should know about this association. this one out Using the example of association, this time the three models should be written like this: has_and_belongs_to_many has_many has_many , belongs_to belongs_to has_many has_many , < ApplicationRecord class User :user_roles :roles through: :user_roles end < ApplicationRecord class UserRoles :user :role end < ApplicationRecord class Role :user_roles :users through: :user_roles end This will enable you to do things like and to get a list of all connected second model instances. It will also enable you to get access to data specific to the relation between first and second models. association user.role Polymorphic are the most advanced associations available to us. You can use it when you have a model that may belong to many different models on a single association. Polymorphic associations Let's imagine you want to be able to write comments for users and stories. You want both models to be commentable. Here's how this could be declared: belongs_to , has_many , has_many , < ApplicationRecord class Comment :commentable polymorphic: true end < ApplicationRecord class Employee :comment as: :commentable end < ApplicationRecord class Product :comment as: :commentable end You can think of a polymorphic `belongs_to` declaration as that any other model can use. To declare the you need to declare both a foreign key column and a type column in the model. You should once you are done. setting up an interface polymorphic interface run the migration create_table t.text t.integer t.string t.timestamps add_index , < ActiveRecord::Migration class CreateComments def change :comments do |t| :body :commentable_id :commentable_type end :comments :commentable_id end end This migration can be simplified by using : references create_table t.text t.references , , t.timestamps < ActiveRecord::Migration class CreateComments def change :comments do |t| :body :commentable polymorphic: true index: true end end end Additional Options There are a few additional options you can use when defining , we will cover two most commonly used ones. relations between models class_name If the name of the other model cannot be derived from the association name, you can use the option to supply the model name. You can read more about this on . :class_name RailsGuides You want the belongs_to relation to call for an , but there are two problems: Example: author There is no model called in that way. The story table is missing an `author_id` field. To make this work and stop your , you just have to specify the and the actual name of the class: Easy fix! tests from failing :foreign_key belongs_to , , < ApplicationRecord class Story :author class_name: 'User' foreign_key: 'user_id' end dependent You can use this option when you want to get rid of since they can lead to various problems. Orphaned records are created when we a model A that was associated with model B, but model B wasn't removed in the process. orphaned records delete or destroy has_many , < ApplicationRecord class User :stories dependent: :destroy end Suppose, a user called Maria wrote a lot of stories. Then, we deleted Maria from the database, but the stories still have the user_id column set to Maria's id. These stories are called . Example: orphaned records Thank you for reading! Previously published at kolosek.com/rails-associations/