Search code examples
ruby-on-railscsvseeding

How can I remove the "\n" character from csv entries?


I am seeding my database with tags written on a file called tags.csv .I was able to seed the tags, however, when I check in my console, I see a character \n as the last character of the tag name. For example, let s say that airplane is the tag name, when I seed, I get the tag name as airplane\n What am I doing wrong ?

My db/tags.csv is the csv file that contains tag entries and it looks like this:

airplane
sleeping
travel 

Now in my seeds.rb file ( that is supposed to be seeding the tags) looks like:

puts "loading tags..."

# LOADING TAGS
GOD_USER_ID = -1
csv_text    = File.read('db/tags.csv')
csv         = CSV.parse(csv_text, :headers => true)

puts "loading tags..."

csv.each_with_index do |row, index| 
  tag = row
  if ActsAsTaggableOn::Tag.exists?(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC') == false then
    ActsAsTaggableOn::Tag.create(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC') 
    if index % 10 == 0
        puts "tag: #{tag} --- index: #{index}"
    end
  else
    if index % 10 == 0
        puts "tag: #{tag}\t(already exists) --- index: #{index}"
    end
  end
end

Solution

  • Use foreach it should work properly

    puts "loading tags..."
    
    # LOADING TAGS
    GOD_USER_ID = -1
    puts "loading tags..."
    
    CSV.foreach("#{Rails.root}/db/tags.csv", headers: true) do |row|
      if ActsAsTaggableOn::Tag.exists?(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC')
        puts "tag: #{tag}\t(already exists) --- index: #{index}" if index % 10 == 0
      else
        ActsAsTaggableOn::Tag.create(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC')
        puts "tag: #{tag} --- index: #{index}" if index % 10 == 0
      end
    end