0

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
vinothini
  • 2,606
  • 4
  • 27
  • 42

1 Answers1

0

I'll do it this way:

class IndustryType < ActiveRecord::Base
  has_many :companies
  has_many :mayors
  has_many :minors
  # keep this if you need a relation with both categories
  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 
end

class Major < Category;
end

class Minor < Category;
end


IndustryType.first.categories -> Returns both major and minor category of that industry type
IndustryType.first.majors -> Returns only major category of that industry type
IndustryType.first.minors -> Returns only minor category of that industry type
Major.all -> Returns all major categories
Minor.all -> Returns all minor categories

I remove the scopes on Category, and associate IndustryType with both types of Category (Minor & Mayor).

How to get specific company major or minor category?

Company.last.industry_type.majors -> Returns major categories of that company based on its industry type.
Company.last.industry_type.minors -> Returns minor categories of that company based on its industry type.
Alejandro Babio
  • 5,189
  • 17
  • 28