rake db:seed在种子时填充键

时间:2012-04-01 07:16:35

标签: ruby-on-rails seed

我在txt文件中有状态数据,我用它来播放我的状态db,它有列:id和:name。 :name是状态的2位数代码。在seeds.rb文件中使用以下代码:

State.delete_all
open("C:/Sites/rails_projects/sales_tracking/lib/assets/states.txt") do |states|
  states.read.each_line do |state|
  name = state
  State.create!(:name => name)
 end
end

我现在拥有包含city,state数据的Cities.txt文件。我的城市数据库有列:id,:name,:state_id。 :state_id是states表中的外键。我需要在seed.rb文件的下面部分添加什么代码来填充:state_id,同时在城市种子数据上运行rake db:seed(“代码”是2位数的状态ID)。

City.delete_all
open("C:/Sites/rails_projects/sales_tracking/lib/assets/cities.txt") do |cities|
  cities.read.each_line do |city|
    name, code = city.chomp.split(",")
     ??
    City.create!(:name => name, :state_id => state_id)
  end
end

1 个答案:

答案 0 :(得分:2)

使用动态查找器获取状态:

City.create!(:name => name, :state => State.find_by_name(code))

或者,如果您想避免一些查询,并且如果状态代码保证存在,您可以在哈希中为它们播种时跟踪状态并将它们重新用于城市:

State.delete_all
City.delete_all

@states = {}

open("states.txt").read.each_line do |code|
  @states[code] = State.create!(:name => code)
end

open("cities.txt").read.each_line do |city|
  name, code = city.chomp.split(",")
  City.create!(:name => name, :state => @states[code])
end