Oliver
Oliver

Reputation: 1181

Rails ID sequence after csv import in Heroku PG database

I'm building a diary for a user to track his daily expenditures. However, I already have csv file that holds 1751 records that I am importing to my expenditures table. I'm doing this via a rake task.

The import works fine. When I am doing so in development (SQLite) and want to create a new record via the create action the new record holds the ID 1752 (which is correct).

If I do so in production (Heroku/PostgreSQL) Postgres tries to create the new record with ID 1 which, obviously, leads to an error (as the first 1751 IDs are already taken).

My question: how can I fix that so that the Postgres ID sequence starts with ID 1752 instead of ID 1 (like SQLite in development)?

import_expenditure.rake

require 'csv'

namespace :csv do

  desc "Import CSV Data from Expenditures data"
  task :import_expenditures => :environment do
    Expenditure.delete_all
    csv_file_path = 'db/exp_data.csv'

    CSV.foreach(csv_file_path) do |row|

        Expenditure.create!({
          :id => row[0],
          :day => row[1],
          :value => row[2],  
          :description => row[3],
          :cost_type => row[4],
          :category_id => row[5],
          :user_id => row[6]
        })
        puts "Row added!"

    end
  end
end

Upvotes: 0

Views: 79

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Try adding this line before the loop

ActiveRecord::Base.connection.execute("SELECT setval('expenditures_id_seq', 1752);"

This will change the value of id column

Upvotes: 1

Related Questions