1

레일 3.1을 사용하고 있습니다. 모델 트리 및 모델 TreeNode가 있고 Tree와 TreeNodes 사이에 has_many/belongs_to 연관을 설정했습니다.레일스에서 ​​서로 다른 방식으로 서로 참조하는 두 모델에 대해 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) 또는 순서 (노드가있는 순서 개념이 없으므로)를 통해 루트 노드를 암시 적으로 결정할 수 없습니다. 레일즈에서이 연관성을 설정하는 방법에 대해 고민하고 있습니다.

이 나는 ​​나무 테이블에 외래 키와 root_node가 열을 추가하여 시작했다,하지만 내 액티브 레코드 협회는 노드와 노드 has_one 트리 belongs_to 트리 될 것입니다. 이는 외부 키가있는 클래스가 "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과 조인 테이블을 생성하려고했습니다 통해,하지만 협회 중 하나가 작동하지 않을 것입니다.

# 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 

말하기 일반적으로이 관계를 모델링하는 가장 좋은 방법은 무엇이고, 액티브의 연결을 설정하는 가장 좋은 방법은 무엇인가? 하루가 끝나면 나는 이렇게 할 수 있기를 바란다.

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 

리프 노드와 하나가 PARENT_ID로 사용되지 않습니다 ID 때입니다. 자세한 내용은 acts_as_tree plugin을 확인하십시오 (레일 3에서 작동하는지 확실하지 않음).

더 유용한 다른 옵션은 nested_set (here)

입니다.
관련 문제