如何解决Rails:如何为同一模型设置多种关系类型
我有一个 Product
和 Category
模型,它们具有 has_and_belongs_to_many
关系。
所以我可以搜索 Product.categories
或 Category.products
class Product < ApplicationRecord
has_and_belongs_to_many :categories
end
class Category < ApplicationRecord
has_and_belongs_to_many :products
end
现在我想为 Product
添加一个新关系:
它应该调用 main_category
,它只应该是从 has_one
到 Product
的 Category
关系。所以一个 Product
只能有一个 MainCategory。但是 Category 当然应该返回所有 MainCategory 产品。
-
我必须创建一个类别的子类吗?通常我不想创建额外的类
-
我该如何解决这个问题,只需调用
Product.main_category
或Category.main_products
? -
如何正确放置索引?
-
迁移应该是什么样子的?
解决方法
我猜你可以简单地这样做
class Product < ApplicationRecord
has_and_belongs_to_many :categories
belongs_to :main_category,class_name: 'Category',foreign_key: :main_category_id
end
class Category < ApplicationRecord
has_and_belongs_to_many :categories
has_many :main_products,class_name: 'Product',foreign_key: :main_category_id
end
您必须向名为 products
的 main_category_id
表添加一列
来源https://guides.rubyonrails.org/association_basics.html#bi-directional-associations
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。