0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsの関連付け データベースレベル

0
Posted at

blongs_to

belongs_toでは「参照の一貫性」が担保されません。
そのため、ユースケースによっては以下のように参照カラムでデータベースレベルの外部キー制約(foreign_key: true)を追加する必要があります。

create_table :books do |t|
  t.belongs_to :author, foreign_key: true
  # ...
end

出典

has_many

ユースケースにもよりますが、通常はこのbooksテーブルのauthorカラムに「一意でない」インデックスを追加し、オプションで外部キー制約を作成するのがよいでしょう。

create_table :books do |t|
  t.belongs_to :author, index: true, foreign_key: true
  # ...
end

出典

気づき

  • インデックスにすれば早くなりそうだ。

3.6 参照

add_referenceメソッドを使うと、適切な名前のカラムを作成できます。

add_reference :users, :role

このマイグレーションは、usersテーブルにrole_idカラムを作成します。index: falseオプションを明示的に指定しない限り、そのカラムのインデックスも作成します。

add_reference :users, :role, index: false

add_belongs_toメソッドはadd_referenceのエイリアスです。

出典

エイリアスとは?

エイリアスとは、偽名、別名、通称などの意味を持つ英単語。ITの分野では、ある対象や実体を、複数の異なるシンボルや識別子で同じように参照できるする仕組みを指す。別名。

出典

気づき

add_belongs_toメソッドはadd_referenceのエイリアスです。は、
名前を変えただけで一緒ということなのかな。

実践

class AddBelongsTo********To***** < ActiveRecord::Migration[7.0]
  def change
    add_belongs_to :テーブル名, :モデル名, index: true, foreign_key: true
    add_belongs_to :テーブル名, :モデル名, index: true, foreign_key: true
  end
end

感想

一応できたと思っている。
時間がかかりすぎた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?