LoginSignup
1
1

More than 5 years have passed since last update.

[Ruby on Rails] SubModel in Model

Posted at
Category
  Sub Category
  Sub Category
  Sub Category
migrate.rb
class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name
      t.references :parent

      t.timestamps
    end
  end
end
model.rb
class Category < ApplicationRecord
  has_many :categories, class_name: 'Category', foreign_key: 'parent_id',
    dependent: :destroy
  belongs_to :parent, class_name: 'Category', optional: true
end

c.parent
c.categories

1
1
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
1
1