I have company, indstry type, major category and minor category in my app. I used single table inheritance for major and minor categories. I have following association.
class IndustryType < ActiveRecord::Base
has_many :companies
has_many :categories
end
class Company < ActiveRecord::Base
belongs_to :industry_type
end
class Category < ActiveRecord::Base
belongs_to :industry_type
def self.types
%w(Major Minor)
end
scope :majors, -> { where(type: 'Major') }
scope :minors, -> { where(type: 'Minor') }
end
class Major < Category;
end
class Minor < Category;
end
IndustryType.first.categories -> Returns both major and minor category of that industry type
IndustryType.first.categories.majors -> Returns only major category of that industry type
IndustryType.first.categories.minors -> Returns only minor category of that industry type
Major.all -> Returns all major categories
Minor.all -> Returns all minor categories
How to get specific company major or minor category?
Company.last.industry_type.categories.majors -> Returns industry based major categories only