基于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'
您需要修改关联parent_category。
在此必须指定外键。
belongs_to :parent_category, class_name: "Category", foreign_key: 'parent_id'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句