【问题标题】:HABTM association associated to single table inheritance与单表继承关联的 HABTM 关联
【发布时间】:2009-06-16 23:28:45
【问题描述】:

我有一个产品模型有很多部分,一个部分可以属于许多产品。

截面模型具有特征、标准和选项的子类。

我的模型是:

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

但它只是“未定义的方法'功能'”等错误。

谁能告诉我怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby has-and-belongs-to-many sti


    【解决方案1】:

    假设您有一个名为“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
    

    【讨论】:

      【解决方案2】:

      产品没有这些方法,因为它们从未被定义。您需要在您的产品类中定义关系以获取功能/标准/选项方法

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

      将使您更好地了解定义关系的含义

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 2016-09-06
        相关资源
        最近更新 更多