如何修复SQLite3 :: ConstraintException:UNIQUE约束失败:

问题描述 投票:0回答:1

我通过导入excel电子表格将多个访客添加到访客列表。

它最初是一个独立的资源,并且一切正常。我能够导入新的来宾列表以及重新导入更新的来宾列表。

我现在在我的事件模型中嵌套了我的来宾列表模型,因此一个事件有很多来宾列表,而一个来宾列表属于一个事件,并且在导入电子表格时出现了错误提示。

据我所知,我对文件进行了正确的更改以进行嵌套,还重置了数据库并运行db:migrate。第一次导入有效,但随后在重新导入相同文件时抛出错误(此操作在原始文件上有效)

旧控制器:

 def import
    Guestlist.import(params[:file])
    redirect_to guestlists_path, notice: "Guest-list 
  Successfully Imported."
   end

新控制器:

 def import
  @guestlists = @event.guestlists.import(params[:file])
  redirect_to event_guestlists_path(@event), notice: "Guest-list Successfully Imported."
end

导入方法:

def self.import(file)
  spreadsheet = Roo::Spreadsheet.open(file.path)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    guestlist = find_by(id: row["id"]) || new
    guestlist.attributes = row.to_hash
    guestlist.save!
  end
end

保存方法:

def save
    if imported_items.map(&:valid?).all?
      imported_items.each(&:save!)
      true
    else
      imported_items.each_with_index do |item, index|
        item.errors.full_messages.each do |msg|
          errors.add :base, "Row #{index + 1}: #{msg}"
        end
      end
      false
    end
  end

访客列表模式:

  create_table "guestlists", force: :cascade do |t|
    t.string "firstname"
    t.string "email"
    t.string "response"
    t.integer "event_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "dietary_requirements"
    t.string "lastname"
    t.index ["event_id"], name: "index_guestlists_on_event_id"
  end

如果需要更多代码,我会相应添加!

提前感谢

来自终端的错误日志:

ActiveRecord::RecordNotUnique (SQLite3::ConstraintException: UNIQUE constraint failed: guestlists.id: INSERT INTO "guestlists" ("id", "firstname", "email", "created_at", "updated_at", "lastname") VALUES (?, ?, ?, ?, ?, ?)):

app/models/guestlist.rb:20:in `block in import'
app/models/guestlist.rb:16:in `import'
app/controllers/guestlists_controller.rb:34:in `import'
Started POST "/events/1/guestlists/import" for ::1 at 2019-10-05 13:19:03 +0200
Processing by GuestlistsController#import as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"UmBvaiHr3s2HJ4WKxBazfRNtVT1E5BLrejPjLhx1IbrlGshEbE8UcaQIilJJeq2m3rGefDtJ65C0iRToZWvOqA==", "file"=>#<ActionDispatch::Http::UploadedFile:0x007fe42d188080 @tempfile=#<Tempfile:/var/folders/sw/t3c38b_d0z343xcp6sznp_h80000gn/T/RackMultipart20191005-44877-kiw9l6.xls>, @original_filename="guestlists (7).xls", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"guestlists (7).xls\"\r\nContent-Type: application/octet-stream\r\n">, "commit"=>"Import Guest List", "event_id"=>"1"}
  User Load (2.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ /Users/ryan/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.2.2.1/lib/active_record/log_subscriber.rb:98
  Event Load (2.3ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/guestlists_controller.rb:111
  Guestlist Load (2.6ms)  SELECT  "guestlists".* FROM "guestlists" WHERE "guestlists"."event_id" = ? AND "guestlists"."id" = ? LIMIT ?  [["event_id", 1], ["id", 1], ["LIMIT", 1]]
  ↳ app/models/guestlist.rb:18
   (0.2ms)  begin transaction
  ↳ app/models/guestlist.rb:20
  Guestlist Create (1.0ms)  INSERT INTO "guestlists" ("id", "firstname", "email", "created_at", "updated_at", "lastname") VALUES (?, ?, ?, ?, ?, ?)  [["id", 1], ["firstname", "ryan"], ["email", "[email protected]"], ["created_at", "2019-10-05 11:19:04.522415"], ["updated_at", "2019-10-05 11:19:04.522415"], ["lastname", "neill"]]
  ↳ app/models/guestlist.rb:20
   (0.1ms)  rollback transaction
  ↳ app/models/guestlist.rb:20
Completed 500 Internal Server Error in 243ms (ActiveRecord: 12.8ms)
ruby sqlite ruby-on-rails-5
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.