Rails reference type creation added

Introduction

This time, I sometimes deal with reference type when migrating with rails, so I will summarize it.

What is a foreign key?

You need to know about foreign keys when working with reference types.

A foreign key is a relational database (RDB) that allows you to enter only the items contained in a specific column of another table in one column of the table. In addition, the column specified at that time http://e-words.jp/w/%E5%A4%96%E9%83%A8%E3%82%AD%E3%83%BC.html#:~:text=%E5%A4%96%E9%83%A8%E3%82%AD%E3%83%BC%E3%81%A8%E3%81%AF%E3%80%81%E3%83%AA%E3%83%AC%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%8A%E3%83%AB,%E3%82%92%E7%94%A8%E3%81%84%E3%81%A6%E8%A8%AD%E5%AE%9A%E3%81%A7%E3%81%8D%E3%82%8B%E3%80%82

This time, set an external key called user_id of reference type in the articles table.

Premise

Prepare user table and ariticle table as sample.


class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string   :name
      t.string   :email
    end
  end
end

class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string   :title
      t.string   :content
    end
  end
end
$ rake db:migrate

Creating a reference type column

If you create it with reference type, it is not added as it is, but it is added with the column name ʻuser_id. It also has the advantage of automatically indexing without adding ʻindex: true.


class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string   :title
      t.string   :content
      t.references :user, foreign_key: true
    end
  end
end

It can also be added using ʻadd_foreign_key`.


class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string   :title
      t.string   :content
    end
      add_foreign_key :articles, :users
  end
end

Add reference type column


class AddReferenceColumn < ActiveRecord::Migration[6.0]
  def change
    add_reference :articles, :user, foreign_key: true
  end
end

Don't forget foreign_key: true again.

Recommended Posts

Rails reference type creation added
[Rails] Many-to-many creation
Basic data type and reference type
Column type quick reference table
Utilization of Rails Boolean type
API creation with Rails + GraphQL
[Rails] New app creation --Notes--
Add & save from rails database creation
Kaminari --Added pagination function of Rails
[Rails] Initial data creation with seed
[Ruby on Rails] Confirmation page creation
What is a reference type variable?
Difference between primitive type and reference type
First pagination feature added in rails
[Rails] haml code quick reference table