2009-06-16 10 views
7

Ich habe ein Produktmodell mit vielen Abschnitten, und ein Abschnitt kann zu vielen Produkten gehören.HABTM-Assoziation, die mit der Vererbung einzelner Tabellen verknüpft ist

Das Abschnittsmodell hat Unterklassen von Feature, Standard und Option.

Meine Modelle sind:

class Product < ActiveRecord::Base 
has_and_belongs_to_many :categories 
has_and_belongs_to_many :sections  
end 

class Section < ActiveRecord::Base 
has_and_belongs_to_many :products 
end 

class Feature < Section 
end 

class Standard < Section 
end 

class Option < Section 
end 

In meiner Produkte Controller kann ich dies tun:

@product.sections.build 

Ich möchte die Unterklassen wie so etwas bekommen können:

@product.features.build 

@product.standards.build 

@product.options.build 

Aber es ist nur Fehler mit "undefined Methode 'Features" usw.

Kann mir bitte jemand sagen, wie man das macht?

Antwort

11

Angenommen, Sie haben einen has_and_belongs_to_many beitreten Tabelle mit dem Namen "products_sections", was Sie benötigen, sind diese zusätzlichen Verknüpfungen in Ihrem Prodcut-Modell:

class Product < ActiveRecord::Base 
has_and_belongs_to_many :sections 
has_and_belongs_to_many :features, association_foreign_key: 'section_id', join_table: 'products_sections' 
has_and_belongs_to_many :standards, association_foreign_key: 'section_id', join_table: 'products_sections' 
has_and_belongs_to_many :options, association_foreign_key: 'section_id', join_table: 'products_sections' 
end