How to Make a belongs_to Relationship in Rails

Jeff Morhous - Jul 7 '23 - - Dev Community

What is belongs_to and has_many in Ruby on Rails

ActiveRecord makes it really easy to tie models in a Rails app to other models.
In fact, you can even specify when you create a model what it should be associated
with. If you already have to models and you would like one model to belong to the other,
you'll need to change both models and create a migration.

Let's say you have a model, Tweet, and another model, User. A user can tweet many times,
and a tweet only belongs to one user. In ActiveRecord speak, User has_many tweets, and
a Tweet belongs_to a User. The database records are tied together, and you can build
features around the association easily.

How to Implement belongs_to and has_many

Continuing on the User/Tweet example, in the Tweet class, simply add belongs_to :user.
The class should look like this:

class Tweet < ApplicationRecord
  belongs_to :user
end
Enter fullscreen mode Exit fullscreen mode

In the User class, simply add has_many :tweets.
The class should look like this:

class Tweet < ApplicationRecord
    has_many :tweets
end
Enter fullscreen mode Exit fullscreen mode

This will tell rails to generate some methods you can use, but you still need to tie
the database records together. Create a new migration by running:

rails generate migration AddUserIdToTweets
Enter fullscreen mode Exit fullscreen mode

In the migration file, make the change method look like this:

  def change
    add_column :tweets, :user_id, :integer
  end
Enter fullscreen mode Exit fullscreen mode

This adds a user_id column to the Tweets database table, which rails will use
to keep track of which user a tweet object belongs to.

How to Get Use a belong_to and has_many relationship

You can use the association to do a number of things, including getting all
tweets that belong to a given user. The call is simple enough, and assuming
current_user refers to a User model, it looks like this:

current_user.tweets
Enter fullscreen mode Exit fullscreen mode

To create a new Tweet that belong to a user, you can do this:

current_user.tweets.build(tweet_params)
Enter fullscreen mode Exit fullscreen mode

Hope this was helpful!

. . . . . . . . . . . . . . . . . . . .