STI 単一テーブル継承

STI 単一テーブル継承

[Tag]モデルと[Author]モデルは、同じカラム名が必要になるので、[Taxonomy]テーブルに[Tags]テーブルと[Author]テーブルの値を保存に[Taxonomy]テーブルのtypeカラムに何のモデルのデータかを保存する

class Taxonomy < ApplicationRecord
  validates :name, presence: true, uniqueness: { scope: :type }, length: { maximum: 16 }
  validates :slug, presence: true, uniqueness: { scope: :type }, length: { maximum: 64 }, slug_format: true
end
class Tag < Taxonomy
  has_many :article_tags
  has_many :articles, through: :article_tags
end
class Author < Taxonomy
  has_many :articles

  has_one_attached :avatar

  validates :avatar, attachment: { purge: true, content_type: %r{\Aimage/(png|jpeg)\Z}, maximum: 10_485_760 }
end
  create_table "taxonomies", force: :cascade do |t|
    t.string "type"
    t.string "name"
    t.string "slug"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["slug"], name: "index_taxonomies_on_slug"
    t.index ["type"], name: "index_taxonomies_on_type"
  end

下記が[Tags]テーブルにデータを保存した時の動き(typeカラムに[Tag]が保存されている)

Image from Gyazo

参考記事:

【Rails】単一テーブル継承(STI)について - Qiita