Skip to content

Instantly share code, notes, and snippets.

@JamesAndresCM
Last active November 10, 2021 13:13
Show Gist options
  • Save JamesAndresCM/6d2af932033389fafc7d5add5049d166 to your computer and use it in GitHub Desktop.
Save JamesAndresCM/6d2af932033389fafc7d5add5049d166 to your computer and use it in GitHub Desktop.
example parent child
# categories without link
rails g model Category name parent_id:integer:index
class Category < ApplicationRecord
has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy
belongs_to :parent, class_name: 'Category', foreign_key: 'parent_id', optional: true
end
# linked_categories
rails g model Category name
rails g model LinkedCategory parent_id:integer child_id:integer
class Category < ApplicationRecord
has_many :linked_categories, foreign_key: 'parent_id'
has_many :subcategories, through: :linked_categories, source: :child
has_many :linked_me, class_name: 'LinkedCategory', foreign_key: 'child_id'
has_many :linked_me_categories, through: :linked_me, source: :parent
def self.main_categories
ids = all.ids - joins(:linked_me).ids
where(id: ids)
end
def self.display_subcategories(el, root_name)
if el.subcategories.present?
el.subcategories.each_with_object([]) do |el, arr|
if el.subcategories.size <= 1
arr << { root: root_name, subcategories: el.name }
else
arr << display_subcategories(el, root_name)
end
end
end
end
end
class LinkedCategory < ApplicationRecord
belongs_to :parent, class_name: 'Category', foreign_key: 'parent_id'
belongs_to :child, class_name: 'Category', foreign_key: 'child_id'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment