Rails get data while using single table inheritance -
i have company, indstry type, major category , minor category in app. used single table inheritance major , minor categories. 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 , minor category of industry type industrytype.first.categories.majors -> returns major category of industry type industrytype.first.categories.minors -> returns minor category of industry type major.all -> returns major categories minor.all -> returns minor categories
how specific company major or minor category?
company.last.industry_type.categories.majors -> returns industry based major categories
i'll way:
class industrytype < activerecord::base has_many :companies has_many :mayors has_many :minors # keep if need relation 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 , minor category of industry type industrytype.first.majors -> returns major category of industry type industrytype.first.minors -> returns minor category of industry type major.all -> returns major categories minor.all -> returns minor categories
i remove scopes on category
, , associate industrytype
both types of category
(minor
& mayor
).
how specific company major or minor category?
company.last.industry_type.majors -> returns major categories of company based on industry type. company.last.industry_type.minors -> returns minor categories of company based on industry type.
Comments
Post a Comment