gpt4 book ai didi

ruby-on-rails - 与单表继承关联的 HABTM 关联

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:05 25 4
gpt4 key购买 nike

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

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

我的模型是:

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

在我的产品 Controller 中我可以这样做:

@product.sections.build

我希望能够像这样访问子类:

@product.features.build

@product.standards.build

@product.options.build

但它只是出现“未定义方法‘特征’”等错误。

谁能告诉我怎么做?

最佳答案

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

关于ruby-on-rails - 与单表继承关联的 HABTM 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1004412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com