![](/img/trans.png)
[英]Rails: How to display categories and subcategories in ruby on rails
[英]How to implement Parent Categories, Categories and Subcategories using self referencing controller in 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
這是我使用此association.find 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
請在這里幫助我,讓我了解對我而言什么是完美的聯想。 請不要給我寶石名稱,例如“祖先”或“ 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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.