January 4, 2023 By Matthew Rathbone *

Rails migration is a process in Ruby on Rails, a popular web application framework, that allows developers to create, modify, and delete database tables and columns. One important aspect of Rails migration is the belongs_to association, which establishes a one-to-one or one-to-many relationship between two models in a Rails application.

👋 Check out our easy to use desktop GUI for SQL

Beekeeper Studio is a truly cross-platform SQL GUI with a clean, uncluttered interface. Write SQL, edit data, alter tables, and more!

Available for MacOS, Linux, and Windows.

The belongs_to association is used to specify that one model “belongs to” another model, meaning that it has a foreign key that references the primary key of the other model. For example, in a blogging application, you might have a Post model and a Category model, with the Post model belongs_to the Category model. This means that each Post record has a foreign key that references the primary key of a Category record, indicating which category the post belongs to.

To set up a belongs_to association in a Rails migration, you can use the belongs_to method in the migration file, which takes the name of the other model as an argument. For example, to create a belongs_to association between the Post and Category models, you might use the following code in your migration file:

class CreatePosts < ActiveRecord::Migration[6.0]
  def change
    create_table :posts do |t|
      t.belongs_to :category, index: true
      t.string :title
      t.text :body

This code creates a new posts table with a foreign key column called category_id that references the id column of the categories table. It also includes an index on the category_id column for faster queries.

Once the migration has been run and the posts and categories tables have been created in the database, you can then set up the belongs_to association in the corresponding model classes. For example, in the Post model class, you might include the following code:

class Post < ApplicationRecord
  belongs_to :category

This tells Rails that the Post model has a belongs_to association with the Category model. You can then use the category method in the Post model to access the associated Category record, and the posts method in the Category model to access the associated Post records.

Using the belongs_to association in your Rails application can make it easier to work with related models and manage database relationships. It also helps to enforce data integrity by ensuring that a foreign key value always references a valid primary key value in the other model’s table.