HABTM association associated to single table inheritance
has-and-belongs-to-many, ruby, ruby-on-rails, sti
Solution
Assuming that you have a has_and_belongs_to_many join table with the name "products_sections", what you would need are these additional associations in your Prodcut model:
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
Problem
I have a product model that has many sections, and a section can belong to many products. The section model has subclasses of Feature, Standard and Option. My models are: ``` 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 my products controller I can do this: ``` @product.sections.build ``` I want to be able to get to the subclasses like something like this: ``` @product.features.build @product.standards.build @product.options.build ``` But it just errors with "undefined method 'features' " etc. Please can anyone tell me how to do this?