ruby-on-rails - 如何在 Rails 4 中使用自引用控制器实现父类别、类别和子类别
问题描述
我正在尝试使用自引用来实现三级深度关联。
Cat1
Sub1
SubSub1
SubSub2
Sub2
Cat2
Sub1
Cat3
Sub1
Sub2
SubSub1
我可以通过这种关系获得一个类别的子类别:
class Category < ActiveRecord::Base
has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
end
当我只有两级深度类别时,这很好。对于使用自引用的三级深度关联,我尝试使用这种关系,但未能获得所需的输出。
class Category < ActiveRecord::Base
belongs_to :parent_category, class_name: "Category"
has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
end
这是我使用此关联得到的结果。触发的查询Category.find(3).parent_category
是错误的。
2.0.0-p648 :012 > Category.find(2)
Category Load (1.2ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 2 LIMIT 1
=> #<Category id: 2, title: "Suit", description: "sffdsfsxcx ssdfvvs", seo_name: "sfsdf", parent_id: nil, hoe_page: nil, status: true, sequence: "1", banner_image_file_name: nil, banner_image_content_type: nil, banner_image_file_size: nil, banner_image_updated_at: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, home_description: "adhkadaa", home_page: true, long_description: "sdfsddfffssssde", created_at: "2018-04-09 07:42:55", updated_at: "2018-04-09 07:42:55">
2.0.0-p648 :013 > Category.find(3)
Category Load (1.1ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 3 LIMIT 1
=> #<Category id: 3, title: "a", description: "aaa", seo_name: "a", parent_id: 2, hoe_page: nil, status: true, sequence: "1", banner_image_file_name: nil, banner_image_content_type: nil, banner_image_file_size: nil, banner_image_updated_at: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, home_description: "aaa", home_page: true, long_description: "aaa", created_at: "2018-04-09 09:44:11", updated_at: "2018-04-09 09:44:11">
2.0.0-p648 :014 > Category.find(3).parent_category
Category Load (1.1ms) SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 3 LIMIT 1
=> nil
请在这里帮助我,让我了解什么是我的目的的完美关联。请不要给我像“Ancestry”或“awesome_nested_set”这样的宝石名称,我需要纯 Rails 关联。
解决方案
尝试这个:
belongs_to :parent_category, foreign_key: :parent_id, class_name: 'Category'
has_many :sub_categories, foreign_key: :parent_id, class_name: 'Category'
推荐阅读
- angular - 在 Angular HTML 输入变量中连接
- machine-learning - TensorFlow 2 XOR 实现
- android - 当应用程序处于后台时,变量保持其值多长时间?
- java - 当达到测试超时时,Maven 肯定会失败构建,即使失败时设置为 true
- c# - 如何记录所有 Rest Api(ApiController) 方法的输出?
- c++ - 如何在 clang libtooling 中启用 try-catch?
- python - How to access the properties of one specific patch from subplot in matplotlib
- python - Python:上下文管理器“生成器”没有实现 __enter__ 和 __exit__
- aws-codepipeline - 我应该如何在我的 CDK 构建脚本中使用来自 aws ECR 存储库的基于 Windows 的自定义构建工具 docker 映像作为环境
- javascript - 如果所有子复选框都未选中,如何取消选中父复选框,反之亦然?