HABTM association associated to single table inheritance
Asked Answered
A

2

9

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?

Assimilative answered 16/6, 2009 at 23:28 Comment(0)
S
14

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
Specimen answered 18/11, 2012 at 20:49 Comment(0)
A
0

Product doesn't have those methods cause they were never defined. You need to define relationships in your products class to get the features/standards/options methods

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

will give you better understanding of what defining relationships is giving you

Advertence answered 17/6, 2009 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.