排列现有数组以播种 Rails 数据库

Permutating an existing array to seed a Rails database

我想用现有对象数组的排列来为我的 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 五年后的第一次尝试,所以如果我有一些 terminology/methodology 错误,我深表歉意 - 如果有任何进一步的信息,请务必要求澄清必需的!提前致谢!

您可以在播种国家/地区后将此代码段添加到您的 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