Question

I'm importing Data from a CSV file (using Smarter CSV). I process this file as follow in a task:

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

From the :user_provided_headers you can see what variables are passed to each Player.

The variables 'grepo_id' and 'name' are staying the same all of the time, but the other variables change over time.

I'm trying to Find_or_create or Update a given user. For referencing a user i use 'grepo_id' as this variable is unique to every player.

But it seems that i'm missing something, whatever i try goes swimming and i think i got the wrong approach here.

What can i do in this Situation to:

  • Find_by 'grepo_id'
  • If exists update other variables (if any changes)
  • If not existing, create.

Cheers

Edit: from the Smarter CSV Documentation

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
Was it helpful?

Solution

Try this - i'm assuming you want to do it for all rows here, rather than the first one, but you can change if it that's not the case

@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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top