Rails - 父/子关系

bco*_*lan 12 ruby-on-rails parent-child associations

我目前正在使用标准的一对一关系来处理父/子关系:

class Category < ActiveRecord::Base
  has_one :category
  belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)

是否有推荐的方法来做或者这样可以吗?

Tob*_*ede 20

您需要调整用于实现此功能的名称 - 指定关系的名称,然后告诉AR该类是什么:

class Category < ActiveRecord::Base
  has_one :child, :class_name => "Category"
  belongs_to :parent, :class_name => "Category" 
end
Run Code Online (Sandbox Code Playgroud)


equ*_*nt8 6

has_many版本:

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
Run Code Online (Sandbox Code Playgroud)


gue*_*o64 5

我发现我必须对@ equivalent8的解决方案做些小改动,以使其适用于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
Run Code Online (Sandbox Code Playgroud)

如果没有foreign_key声明,Rails会尝试通过organization_id(而不是parent_id和扼流圈)查找子代。

Rails也会在没有:optional => true声明盟友_关联的情况下窒息,因为belongs_to要求在Rails 5中默认分配一个实例。在这种情况下,您将必须分配无限数量的父级。