mercredi 16 mai 2018

How to implement Parent Categories, Categories and Subcategories using self referencing controller in Rails 4

I am trying to implement a three level deep association using self referencing.

Cat1
    Sub1
        SubSub1
        SubSub2
    Sub2
Cat2
    Sub1
Cat3
    Sub1
    Sub2
        SubSub1

I am able to get the child category of a category by this relation:

class Category < ActiveRecord::Base
  has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
end

This is fine when i have only two level deep category. For three level deep association using self referencing i tried using this relation, but failed to get the desired output.

class Category < ActiveRecord::Base
  belongs_to :parent_category, class_name: "Category"
  has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
end

here is what i get using this association.query fired on Category.find(3).parent_category is wrong.

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 

Please help me here by making me understand what would be the perfect association for my purpose. Please dont give me gem name like "Ancestry" or "awesome_nested_set", I need pure rails associations.

Aucun commentaire:

Enregistrer un commentaire