1

我正在使用Rails 3.1。我有一個模型樹和一個模型TreeNode,並且我在Tree和TreeNodes之間建立了has_many/belongs_to關聯。在Rails中,如何使兩個以不同方式引用對象的模型創建ActiveRecord關聯?

# The initial models and associations. 

class Tree < ActiveRecord::Base 
    has_many :tree_nodes 
end 

class TreeNode < ActiveRecord::Base 
    belongs_to :tree 
end 

我想添加根節點的概念,它不一定是首先創建的節點。我不能通過created_date,主鍵(id)或順序(因爲沒有節點的順序概念)來隱式確定根節點。我正在試圖圍繞如何在Rails中設置此關聯。

我開始時在Tree表上添加了一個帶有外鍵的root_node列,但是我的Active Record關聯會成爲樹belongs_to節點和節點has_one樹。這是因爲具有外鍵的類應該具有「belongs_to」關聯,而另一個類應該具有「has_one」關聯。這聽起來不正確。

# This code didn't work. 

class Tree < ActiveRecord::Base 
    has_many :script_steps 
    belongs_to :root_tree_node, :class => 'TreeNode' 
end 

class TreeNode < ActiveRecord::Base 
    belongs_to :tree 
    has_one :tree 
end 

我也嘗試用has_one:through創建一個連接表,但這些關聯也不起作用。

# This code didn't work. 

class Tree < ActiveRecord::Base 
    has_many :script_steps 
    has_one :root_node, :class => 'TreeNode', :through => :root_tree_node 
end 

class TreeNode < ActiveRecord::Base 
    belongs_to :tree 
    has_one :root_tree_node 
end 

# This represents the join table. 
class RootTreeNode < ActiveRecord::Base 
    belongs_to :tree 
    belongs_to :tree_node 
end 

一般來說,建立這種關係的最佳方式是什麼?在ActiveRecord中設置關聯的最佳方式是什麼?在一天結束時,我希望能夠做到這樣的事情。

tree = Tree.create 
some_node = tree.tree_nodes.create 
another_node = tree.tree_nodes.create 

tree.root_node = another_node 
tree.save 

回答

0

嗯......如果你想獲得像例如類別樹正常樹結構中軌做到這一點的一種方式是這樣的:

def Category < ActiveRecord::Base 
    belongs_to :parent, :class_name => "Category", :foreign_key => :parent_id 
end 

這意味着,每一行都有參考其家長。 根節點是一個與

parent_id == nil 

葉節點時,它的ID從來沒有用作PARENT_ID。欲瞭解更多信息,請查看acts_as_tree plugin(不知道它是否適用於導軌3)。 (更多here

相關問題