samedi 7 novembre 2015

update method of ActiveRecord failed because UNIQUE constraint failed: items.id

In this case,

product = <Item id: 4, url: nil, memo: nil, created_at: "2015-11-07 09:48:36", updated_at: "2015-11-07 09:48:36", Totalweight: 390.0, Perweight: nil, price: 1000>
attr = {"id"=>4, "tag_list"=>"peanuts", "price"=>1000, "url"=>nil, "Totalweight"=>390, "memo"=>nil}

I did to update Item's a record.

product.update!(attr)

but error said,

SQLite3::ConstraintException UNIQUE constraint failed: items.id
!! #<ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: items.id: INSERT INTO "items" ("id", "price", "Totalweight", "created_at", "updated_at", "url") VALUES (?, ?, ?, ?, ?, ?)>

Of course id is same because I want to update the record. i tried

product.update_attributes(attr)

also shows same error.

Question is How can I update this Item object?

ActiveRecord's save method is working if id is not set.

in addition, more information, Im using gem 'roo' that import Excel, CSV files and can parse. http://ift.tt/1iJN7XU argument row is from gem 'roo'

here is the code,

  COLUMN = ["id","tag_list","price","url","Perweight","Totalweight", "memo", "id", "created_at", "updated_at"]

  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      if Item.find(row["id"]) then
        product = Item.new
        attr = row.slice(*COLUMN)
        # product.attributes = attr
        product.update(attr)
      else
        product = Item.new
        attr = row.slice(*COLUMN)
        product.attributes = attr
        product.save!
      end
    end
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then
      Roo::Spreadsheet.open(file.path, extension: :csv)
    when ".xls" then
      Roo::Spreadsheet.open(file.path, extension: :xls)
    when ".xlsx" then
      Roo::Spreadsheet.open(file.path, extension: :xlsx)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

Aucun commentaire:

Enregistrer un commentaire