数据映射器仅从循环中保存最后一个元素

时间:2017-03-10 05:21:38

标签: ruby datamapper

将保存最后一个元素。您可以运行脚本17次并保存所有内容。会发生什么?!

class Cities
  include DataMapper::Resource
  property :id, Serial
  property :header, String
  default_scope(:default).update(:order => [:id.desc])
end

@countries = [ "Mumbai", "Delhi", "Bengaluru", "Hyderabad", "Ahmedabad", "Accra", "Kumasi", "Lagos", "Kano", "Ibadan", "Beijing", "Shanghai", "Guangzhou", "Hangzhou", "Chongqing", "Wuhan" ]

c = Cities.new

@countries.each { |x| 
 c.header = x
 c.save
}

1 个答案:

答案 0 :(得分:0)

由于c在循环外被初始化,所以你只是一次又一次地覆盖同一个对象。

解决方案是在循环中移动c初始化,如下所示:

@countries.each { |x|
  c = Cities.new
  c.header = x
  c.save
}

或仅仅是:

@countries.each { |x|
  Cities.create!(header: x)
}

此外,您的型号名称应该是单数,而不是复数。因此,您应该将其命名为City,而不是Cities

另外,请将您的循环变量名更具描述性,因此可以将其称为x而不是country