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?

Brad Werth
  • 17,411
  • 10
  • 63
  • 88

2 Answers2

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
jhilden
  • 145
  • 1
  • 6
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

ErsatzRyan
  • 3,033
  • 1
  • 26
  • 30