2015-03-02 31 views
2

我想將我的Rails應用程序數據庫與現有的對象數組進行排序,並且我不確定關於此的最佳方法。排列現有的數組以種子Rails數據庫

我現在有一個Country模型,具有以下屬性:

create_table :countries do |t| 
    t.string :name 
    t.float :latitude_dec 
    t.float :longitude_dec 

    t.timestamps null: false 
end 

我已經播種從.yaml文件這個模型(因爲這些屬性是靜態的),現在想用這些記錄種子CountryPair模型(其中屬性也是靜態的)。這種模式將具有以下屬性:

create_table :country_pairs do |t| 
    t.string :country_a 
    t.string :country_b 
    t.string :pair_name 
    t.float :country_a_latitude_dec 
    t.float :country_b_latitude_dec 
    t.float :country_a_longitude_dec 
    t.float :country_b_longitude_dec 
    t.float :distance 

    t.timestamps null: false 
end 

目的是重排列Country對象數組,並創建從每個置換一個CountryPair對象(和種子與輸出的數據庫)。我瞭解Ruby array#permutation方法,但我不確定如何將適當的值提取到新的CountryPair對象數組中。這兩個國家的順序在這裏很重要,所以我想使用排列而不是組合。

最終,我還想計算兩個國家對之間的距離,但我希望一旦我有了CountryPair型號就可以開始計算!

這是我第一次進入Rails後五年缺席,所以道歉,如果我有一些術語/方法論錯誤 - 請要求澄清,如果需要進一步的信息!提前致謝!

+0

'Country.all.permutations(2){| CountryPair.create(country_a:pair [0] .name,country_b:pair [1] .name,...}'?如果你希望它成爲數據庫演變的一部分,你可以在遷移中做到這一點。 – Jon 2015-03-02 18:01:16

+0

@Jon謝謝你的迴應 - 僅僅爲了我的理解,它創建了一個新的排列數組'pair',然後你將屬性從' – Budgie 2015-03-02 18:28:39

+0

正確'。這個對包含兩個'Country'對象,這就是爲什麼我們可以做' pair [0] .name'。 – Jon 2015-03-02 19:05:38

回答

1

在國家播種後,您可以將此片段添加到您的seeds.rb中。

Country.all.permutation(2) do |p| 
    CountryPair.create(
    country_a: p[0].name, 
    country_b: p[1].name, 
    pair_name: p[0]name + p[1].name, 
    country_a_latitude_dec: p[0].latitude.dec, 
    country_b_latitude_dec: p[1].latitude.dec, 
    country_a_longitude_dec: p[0].longitude.dec, 
    country_b_longitude_dec: p[1].longitude.dec, 
    distance: # An algorithm to calculate distance 
) 
end 

然後與運行:|對rake db:setup

+0

看起來不錯,歡呼! – Budgie 2015-03-02 18:59:32