Duplicate key violates unique constraint

I’ve run into an interesting issue. When setting up a table with data
from a file (I’m doing this in a block). I find that I can’t create
separate entries manually after the import. It complains about a
duplicate primary key. I’ve tried Schedule.id += 1 but id= either
isn’t defined or accessible in the class

Here is my code:

FasterCSV.foreach("schedule_store/#{@schedule_file.filename}",

“r”) do |row|
unless row[3] == “CRN”

    # This would be faster as straight SQL if the current method
    # slows down too much.
    #
    # Would probably be cleaner with straight SQL too.

    self.associate(row[0], row[1])

    self.first_name = row[0]
    self.last_name = row[1]
    self.place = row[2]
    self.crn = row[3]
    self.course = row[4]
    self.title = row[5]
    self.mx = row[6]
    self.enr = row[7]
    self.avl = row[8]
    self.days = row[9]
    self.start_time = row[10]
    self.end_time = row[11]
    self.start_date = row[12]
    self.end_date = row[13]

    self.create
    self.id += 1
    # Schedule.id += 1
  end
end

Anyone know how I can get Rails to realize what the current id is
after the automated import?

Thanks,
Glen

Is each row instance creating a new id and therefore starting at 1?
Is each row an active record object of the same kind?

On May 1, 10:36 am, “[email protected][email protected]

If I put the code in the controller rather than the model and do a
save rather than create it works fine. I’d rather put this code in
the model though.

Also how do you reset the id sequence back to one? I need to do this
when I clear out the old data and import new data as these schedules
could possibly get rather long and I don’t know how long this program
will be used.

On May 1, 9:36 am, “[email protected][email protected]

I don’t know exactly what the cause of your problem is, but I have a
suspicion. In postgres, you may have a table called ‘schedules’ and
there will also then be a table called ‘schedules_id_seq’. This
specifies the last id used in schedules. If your last serial id in
schedules was 499, then this will be noted in schedules_id_seq. This
value in schedules_id_seq needs to be adjusted to the highest id of
the rows that you imported back after recreating the table, otherwise
trying to insert anything with an id of less than 499 will give
precisely the type of error your server[and thus you] raised.

I hope this is helpful.

David

On May 1, 10:36 am, “[email protected][email protected]

Sorry,

I thought you were running a script outside of your app to add data to
the database.

Maybe you can put the code in a helper and call it from the
controller?

On May 1, 11:03 am, “[email protected][email protected]

Thanks guys, DavidB your suggestion sounds like it might solve my
problems.

Sean I probably should put it in a helper anyway.

Thanks again.