Adding A Reference with Different Model Name in Rails 7

Patrick Karsh
1 min readApr 17, 2023

--

In Rails 7, you can add a reference to a model with a different name by using the references method and the :to_table option in a migration. Here's an example of how you might do this:

First, generate a migration for adding the reference

rails generate migration AddModelNameReferenceToOtherModel

Replace ModelName with the name of the model you want to reference, and OtherModel with the name of the model you're adding the reference to.

Modify the generated migration file in db/migrate

Let’s assume you want to add a reference to a Product model, but the table is named items in the database, and you want to add the reference to an Order model. Your migration file would look like this:

class AddModelNameReferenceToOtherModel < ActiveRecord::Migration[7.0]
def change
add_reference :orders, :product, null: false, foreign_key: { to_table: :items }
end
end

In this example, we’re adding a reference to the Product model in the Order model, but the Product model's table in the database is named items. We use the :to_table option to specify the correct table name for the foreign key.

Run the migration

class Order < ApplicationRecord
belongs_to :product, class_name: "Item"
end

In app/models/item.rb (assuming this is the model for the Product)

class Item < ApplicationRecord
has_many :orders
end

Now, you have successfully added a reference to the Product model with a different table name in Rails 7.

--

--

Patrick Karsh
Patrick Karsh

Written by Patrick Karsh

NYC-based Ruby on Rails and Javascript Engineer leveraging AI to explore Engineering. https://linktr.ee/patrickkarsh

No responses yet