Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

ruby on rails - Creating a model that has a tree structure

I have categories that are in a tree structure. I am trying to link them together by defining a parent for each one. (I couldn't figure out how to call the property parent so it's just category for now, but it means the parent).

class Category < ActiveRecord::Base

    has_one :category # the parent category

end 

But the relationship ends up the wrong way around.

The getter function is on the child category (correctly) but the category_id is stored on the parent:

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" (!!)

The parent needs to be able to have multiple children so this isn't going to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you're looking for is self joins. Check this section of the Rails guide out: http://guides.rubyonrails.org/association_basics.html#self-joins

class Category < ActiveRecord::Base
??has_many :children, class_name: "Category", foreign_key: "parent_id"
??belongs_to :parent, class_name: "Category"
end

Every Category will belong_to a parent, even your parent categories. You can create a single category parent that your highest level categories all belong to, then you can disregard that information in your application.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...