Rails - Parent/child relationships

2019-03-25 04:47发布

I'm currently using a standard one-to-one relationship to handle parent/child relationships:

class Category < ActiveRecord::Base
  has_one :category
  belongs_to :category
end

Is there a recommended way to do it or is this ok?

4条回答
乱世女痞
2楼-- · 2019-03-25 05:04

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
查看更多
够拽才男人
3楼-- · 2019-03-25 05:08

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.

查看更多
不美不萌又怎样
4楼-- · 2019-03-25 05:29

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
查看更多
趁早两清
5楼-- · 2019-03-25 05:29

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"

查看更多
登录 后发表回答