9

多くのセクションを持つ製品モデルがあり、セクションは多くの製品に属することができます。

セクション モデルには、Feature、Standard、および Option のサブクラスがあります。

私のモデルは次のとおりです。

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

私の製品コントローラーでは、これを行うことができます:

@product.sections.build

次のようなサブクラスにアクセスできるようにしたい:

@product.features.build

@product.standards.build

@product.options.build

しかし、「未定義のメソッド「機能」」などでエラーが発生するだけです。

誰でもこれを行う方法を教えてください。

4

2 に答える 2

14

「products_sections」という名前の has_and_belongs_to_many 結合テーブルがあると仮定すると、Prodcut モデルに次の追加の関連付けが必要になります。

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
于 2012-11-18T20:49:33.577 に答える
0

これらのメソッドが定義されていないため、製品にはこれらのメソッドがありません。機能/標準/オプションのメソッドを取得するには、製品クラスで関係を定義する必要があります

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

関係を定義することで得られるものをよりよく理解できるようになります

于 2009-06-17T13:35:49.197 に答える