如何在Rails 4中使用自引用控制器实现父类别,类别和子类别

时间:2018-05-16 12:46:55

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-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上使用此关联.query的错误。

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”,我需要纯粹的铁轨协会。

1 个答案:

答案 0 :(得分:0)

试试这个:

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