我有树结构的类别.我试图通过为每个人定义父母来将他们联系在一起.(我无法弄清楚如何调用该属性parent所以它只是暂时category,但它意味着父母).
class Category < ActiveRecord::Base
has_one :category # the parent category
end
Run Code Online (Sandbox Code Playgroud)
但这种关系最终走错了方向.
getter函数在子类别上(正确)但category_id存储在父类中:
parent = Category.create(:name => "parent")
child = Category.create(:name => "child", :category => parent)
parent.id # 1
child.id # 2
child.category_id # nil
parent.category_id # 2
child.category.name # "parent" (!!)
Run Code Online (Sandbox Code Playgroud)
父母需要能够有多个孩子,所以这不会起作用.