class Node belongs_to :parent,:class_name =>Node has_many :children,:class_name =>Node :foreign_key =>:parent_id end
end
可以看出,我使用的是一個自關聯表,通過自己:parent_id這個鍵將本表自己關聯起來,
現在介紹怎么用factory_girl模擬這樣的模擬結構
首先介紹從葉子結點像root結點一個一對一的模型結構
代碼如下
FactoryGirl.define do factory :node do title "XXXXX" factory :node_leaf ,:class => :node do
association :parent,:factory =>:node end end
通過association這個值,我們將node與node_leaf做成一對一關聯
然后我們再構建root結點向leaf結點一個一對多的情況
FactoryGirl.define do factory :node do title "XXXXX" factory :node_root,:class => :node do after_create do |node| node.children <<FactoryGirl.create(:node,:parent => node) node.children <<FactoryGirl.create(:node,:parent => node) node.children <<FactoryGirl.create(:node,:parent => node) end end end end