2017-07-17 66 views
3

試圖爲嵌套區域記錄創建工廠。爲此,我使用ancestry寶石。地區是地方FactoryGirl - 如何創建記錄層次結構?

關聯實體

地點工廠:

factory :place, traits: [:pageable] do 
    ... 
    association :region, factory: :nested_regions 
end 

地區工廠:

factory :region do 
    level 'area' 
    factory :nested_regions do |r| 
    # create South Hampton region sequence 
    continent = FactoryGirl.create(:region, 
            level: Region.levels[:continent], 
            name: 'Europe ') 
    country = FactoryGirl.create(:region, 
           level: Region.levels[:country], 
           name: 'United Kingdom', 
           parent: continent) 
    state = FactoryGirl.create(:region, 
           level: Region.levels[:state], 
           name: 'England', 
           parent: country) 
    county = FactoryGirl.create(:region, 
           level: Region.levels[:county], 
           name: 'Hampshire', 
           parent: state) 
    name 'Southampton' 
    parent county 
    end 
end 

當我把調試到:nested_regions工廠我看到的是,這些區域的層次結構已經建立,但在Place的before_validation掛鉤Region.all內只返回'Southhampton'地區。使用FactoryGirl實例化整個區域層次結構的正確方法是什麼?

回答

1

不要爲此使用變量。爲每個級別創建單獨的工廠,並使用它如下:

factory :region do 
    name 'Region' 

    factory :county 
    association :parent, factory: :region 
    level 'county' 
    end 

    factory :area 
    association :parent, factory: :county 
    level 'Area' 
    name 'area'  
    end 
end