我的应用程序中有公司,种类,主要类别和次要类别。我对主要和次要类别使用单表继承。我有以下关联。
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
如何获得特定公司的主要或次要类别?
Company.last.industry_type.categories.majors -> Returns industry based major categories only
答案 0 :(得分:0)
我会这样做:
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
我删除Category
上的范围,并将IndustryType
与Category
Minor
和Mayor
两种类型相关联。
如何获得特定公司的主要或次要类别?
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.