Skip to content

Instantly share code, notes, and snippets.

@seak0503
Created January 11, 2017 10:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seak0503/8c19fc65e129bf1262347efab45353c8 to your computer and use it in GitHub Desktop.
Save seak0503/8c19fc65e129bf1262347efab45353c8 to your computer and use it in GitHub Desktop.
railsで再帰リレーションテーブルを作る例

マイグレーションファイル

class CreateServices < ActiveRecord::Migration
  def change
    create_table :services do |t|
      t.references :parent_service       # 親分類への再帰リレーション
      t.string :service_id, null: false  # サービスID
      t.string :name, null: false        # サービス名
      t.text :note                       # 備考

      t.timestamps
    end

    add_index :services, :parent_service_id
    add_index :services, :service_id, unique: true
    add_index :services, :name, unique: true
    add_foreign_key :services, :services, column: 'parent_service_id'
  end
end

モデル

class Service < ActiveRecord::Base
  belongs_to :parent_service_id, class_name: 'Service'
  has_many :child_services, class_name: 'Service', foreign_key: 'parent_service_id', dependent: :nullify
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment