Rails - Parent/child relationships

£可爱£侵袭症+ 提交于 2019-12-03 11:11:46

You will need to tweak the names you are using to get this working - you specify the name of the relationship, and then tell AR what the class is:

class Category < ActiveRecord::Base
  has_one :child, :class_name => "Category"
  belongs_to :parent, :class_name => "Category" 
end

has_many version:

class Category < ActiveRecord::Base
  has_many :children, :class_name => "Category"
  belongs_to :parent, :class_name => "Category" 
end

#migratio
class CreateCategories < ActiveRecord::Migration 
 def change
    create_table :categories do |t|
      t.integer :parent_id
      t.string  :title

      t.timestamps null: false
    end
 end
end

# RSpec test 
require 'rails_helper'
RSpec.describe Category do
  describe '#parent & #children' do
    it 'should be able to do parent tree' do
      c1 = Category.new.save!
      c2 = Category.new(parent: c1).save!

      expect(c1.children).to include(c2)
      expect(c2.parent).to eq c1
    end
  end
end

I found that I had to make a minor change to @equivalent8's solution to make it work for Rails 5 (5.1.4):

class Category < ActiveRecord::Base
  has_many :children, :class_name => "Category", foreign_key: 'parent_id'
  belongs_to :parent, :class_name => "Category", foreign_key: 'parent_id', :optional => true
end

Without the foreign_key declaration, Rails tries to find the children by organization_id instead of parent_id and chokes.

Rails also chokes without the :optional => true declaration on the belongs_to association since belongs_to requires an instance to be assigned by default in Rails 5. In this case, you would have to assign an infinite number of parents.

Since the relation is symmetric, I actually find that different than what Toby wrote, that I prefer the following:

class Category < ActiveRecord::Base 
  has_one :parent, :class_name => "Category" 
  belongs_to :children, :class_name => "Category"
end

For some reason "has one parent, many children" is the way my mind things, not "has many parents, only one child"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!