Ruby on rails 如果用户存在更新变量,则创建新变量(查找或创建)
我正在从CSV文件导入数据(使用)。我在任务中按如下方式处理此文件:Ruby on rails 如果用户存在更新变量,则创建新变量(查找或创建),ruby-on-rails,ruby,csv,import,Ruby On Rails,Ruby,Csv,Import,我正在从CSV文件导入数据(使用)。我在任务中按如下方式处理此文件: require 'smarter_csv' desc "Import Players from World data" task :import => [:environment] do file = "db/data/players.txt" SmarterCSV.process(file, { :user_provided_headers => [ "grepo_id", "
require 'smarter_csv'
desc "Import Players from World data"
task :import => [:environment] do
file = "db/data/players.txt"
SmarterCSV.process(file, {
:user_provided_headers => [
"grepo_id", "name", "alliance_id", "points", "rank", "towns"
], headers_in_file: false
}) do |array|
# post-process the data from each row
array.each do |a|
a[:name] = CGI::unescape(a[:name]).force_encoding('UTF-8')
end
# Create Player
Player.create(array.first)
end
end
从:用户提供的\u标题中
可以看到传递给每个玩家的变量
变量'grepo\u id'
和'name'
始终保持不变,但其他变量会随时间而变化
我正在尝试查找或\u创建
或更新
给定用户。为了引用用户,我使用了'grepo\u id'
,因为这个变量对每个玩家都是唯一的
但我似乎错过了一些东西,无论我尝试什么,我都会去游泳,我想我在这里走错了路
在这种情况下,我可以做些什么:
- 通过
'grepo\u id'查找\u
- 如果存在,更新其他变量(如果有任何更改)
- 如果不存在,请创建
SmarterCSV.process(filename) do |array|
# we're passing a block in, to process each resulting hash / =row (the block takes array of hashes)
# there is only one hash in each array
MyModel.create( array.first )
end
试试这个——我假设您希望对这里的所有行都这样做,而不是第一行,但是如果不是这样,您可以进行更改
@users = []
array.each do |row|
row[:name] = CGI::unescape(row[:name]).force_encoding('UTF-8')
user = User.find_by_grepo_id(row[:grepo_id]) || User.new
user.update_attributes(row)
@users << user
end
@users=[]
array.do每行|
行[:name]=CGI::unescape(行[:name])。强制_编码('UTF-8')
user=user.find_by_grepo_id(行[:grepo_id])| | user.new
user.update_属性(行)
@用户可以解释为什么我们需要使用players=[]和players,您可以在这里使用映射
,只需将数组返回给@users
,是的,但通常您可能希望在结果视图页上显示新创建的播放器,或者类似的内容。如果没有,那么你就不需要在变量中收集它们了。@Engineersky你可以,但我从来都不喜欢在地图块中做永久性的更改:感觉不对。对我来说,“地图”应该只是用来获取数据,而不是进行更新。