首页 > 解决方案 > 如何在 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 关联。

标签: ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4

解决方案


尝试这个:

  belongs_to :parent_category, foreign_key: :parent_id, class_name: 'Category'
  has_many :sub_categories, foreign_key: :parent_id, class_name: 'Category'

推荐阅读