2

基于http://guides.rubyonrails.org/association_basics.html#self-joins

我创建了一个名为 Category 的自联接模型

rails g model Category name parent_id:integer

我改变了模型 category.rb 如下

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

现在在控制台中,我创建了两条 Category 记录

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

a.sub_categories << b
a.save

现在

a.sub_categories # returns Dog

然而

b.parent_category # returns nil

如何让 parent_category 正确返回单父记录?

另外,如果我这样做b.parent_category = a

我收到以下错误

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

1 回答 1

7

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'
于 2013-08-11T06:14:24.963 回答