Rails在使用单表继承时获取数据

时间:2015-04-25 21:11:00

标签: ruby-on-rails single-table-inheritance

我的应用程序中有公司,种类,主要类别和次要类别。我对主要和次要类别使用单表继承。我有以下关联。

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

1 个答案:

答案 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上的范围,并将IndustryTypeCategory MinorMayor两种类型相关联。

如何获得特定公司的主要或次要类别?

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.