大佬教程收集整理的这篇文章主要介绍了Rails:如何为同一模型设置多种关系类型,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 Product
和 category
模型,它们具有 has_and_belongs_to_many
关系。
@R_966_9447@搜索 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
添加一个新关系:
它应该调用 @H_406_3@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
的 @H_406_3@main_category_id 表添加一列
来源https://guides.rubyonrails.org/association_basics.html#bi-directional-associations
以上是大佬教程为你收集整理的Rails:如何为同一模型设置多种关系类型全部内容,希望文章能够帮你解决Rails:如何为同一模型设置多种关系类型所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。