shankardevy
shankardevy

Reputation: 4370

getting parent in self referential model

Based on http://guides.rubyonrails.org/association_basics.html#self-joins

I created a self join model called Category

rails g model Category name parent_id:integer

I altered the model category.rb as below

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

Now in console I'm creating two records of Category as

a = Category.create(name: "Animal")
b = Category.create(name: "Dog")

a.sub_categories << b
a.save

Now

a.sub_categories # returns Dog

however

b.parent_category # returns nil

How do I get parent_category return the single parent record correctly?

Also if I do b.parent_category = a

I get the following error

ActiveModel::MissingAttributeError: can't write unknown attribute 'parent_category_id'

Upvotes: 2

Views: 1945

Answers (1)

Bachan Smruty
Bachan Smruty

Reputation: 5734

You need to modify the association parent_category.

There you have to specify the foreign key.

belongs_to :parent_category, class_name: "Category", foreign_key: 'parent_id'

Upvotes: 7

Related Questions