【问题标题】:Rails/MySQL ActiveRecord::RecordNotUniqueRails/MySQL ActiveRecord::RecordNotUnique
【发布时间】:2017-07-12 10:07:22
【问题描述】:

我有这个令人困惑的错误消息ActiveRecord::RecordNotUnique

这是我的模型:artisan.rb

class Artisan < ActiveRecord::Base
  require 'csv'

  validates :nom_entreprise, presence: true
  validates :nom_entreprise_format_url, presence: true
  validates :adresse_1, presence: true
  validates :code_postal, presence: true
  validates :ville, presence: true
  validates :gps_latitude, presence: true
  validates :gps_longitude, presence: true
  validates :url_site_artisan, presence: true
  validates :telephone, presence: true

  csv_text = File.read('artisans.csv')
  csv = CSV.parse(csv_text, :headers => true)
  csv.each do |row|
    Artisan.create!(row.to_hash)
  end
end

控制器:

class ArtisansController < ApplicationController
  def index
    @artisans = Artisan.all 
  end
end

我也给你schema.rb

  create_table "artisans", force: :cascade do |t|
    t.string   "nom_entreprise",            limit: 255
    t.string   "nom",                       limit: 255
    t.string   "prenom",                    limit: 255
    t.string   "adresse_1",                 limit: 255
    t.string   "adresse_2",                 limit: 255
    t.integer  "code_postal",               limit: 4
    t.string   "ville",                     limit: 255
    t.float    "gps_latitude",              limit: 24
    t.float    "gps_longitude",             limit: 24
    t.string   "description",               limit: 255
    t.string   "url_site_artisan",          limit: 255
    t.string   "url_voir_plus",             limit: 255
    t.float    "telephone",                 limit: 24
    t.string   "nom_entreprise_format_url", limit: 255
    t.boolean  "visible_site_web"
    t.datetime "created_at",                            null: false
    t.datetime "updated_at",                            null: false
  end

最后但并非最不重要的是,错误消息:

Started GET "/admin/artisans" for ::1 at 2017-07-12 11:40:37 +0200
Processing by RailsAdmin::MainController#index as HTML
  Parameters: {"model_name"=>"artisans"}
[RailsAdmin] Could not load model Artisans, assuming model is non existing. (uninitialized constant Artisans)
   (0.2ms)  BEGIN
  SQL (1.0ms)  INSERT INTO `artisans` (`id`, `nom_entreprise`, `nom`, `prenom`, `adresse_1`, `adresse_2`, `code_postal`, `ville`, `gps_latitude`, `gps_longitude`, `description`, `url_site_artisan`, `url_voir_plus`, `telephone`, `nom_entreprise_format_url`, `visible_site_web`, `created_at`, `updated_at`) VALUES (10, 'La Brasserie du Baril', 'NULL', 'NULL', '4, Rue Champlain', 'NULL', 29200, 'Brest', 48.3818645, -4.529462500000022, 'NULL', 'http://www.brasseriedubaril.com', 'NULL', 9.0, 'la-brasserie-du-baril', 1, '2017-07-12 09:40:37', '2017-07-12 09:40:37')
   (0.2ms)  ROLLBACK
Completed 500 Internal Server Error in 24ms (ActiveRecord: 1.4ms)

ActiveRecord::RecordNotUnique (Mysql2::Error: Duplicate entry '10' for key 'PRIMARY': INSERT INTO `artisans` (`id`, `nom_entreprise`, `nom`, `prenom`, `adresse_1`, `adresse_2`, `code_postal`, `ville`, `gps_latitude`, `gps_longitude`, `description`, `url_site_artisan`, `url_voir_plus`, `telephone`, `nom_entreprise_format_url`, `visible_site_web`, `created_at`, `updated_at`) VALUES (10, 'La Brasserie du Baril', 'NULL', 'NULL', '4, Rue Champlain', 'NULL', 29200, 'Brest', 48.3818645, -4.529462500000022, 'NULL', 'http://www.brasseriedubaril.com', 'NULL', 9.0, 'la-brasserie-du-baril', 1, '2017-07-12 09:40:37', '2017-07-12 09:40:37')):
  app/models/artisan.rb:17:in `block in <class:Artisan>'
  app/models/artisan.rb:16:in `<class:Artisan>'
  app/models/artisan.rb:1:in `<top (required)>'

开头的错误消息说模型“工匠”无法加载,因为它不存在。这是真的!为了创建这个模型,我运行了 rails g model Artisannot rails g model Artisans

最后一件事:错误发生在管理界面和视图中(视图中还没有任何内容)。 我能够在管理员中看到 Artisan 的内容,然后离开并显示错误消息。

任何形式的帮助将不胜感激! :)

【问题讨论】:

  • 我猜你的 csv 也有 ID 的值,你不应该手动将其插入数据库。即row.to_hash 将有一个密钥ID,跳过它。 Rails 应该处理该列
  • 跳过它使用row.to_hash.except(:id_column_name)

标签: mysql ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

在 SQL 中,PRIMARY KEY 约束唯一标识数据库表中的每条记录。主键必须包含 UNIQUE 值,并且不能包含 NULL 值。而且,一张表只能有一个主键。 默认情况下,Rails 负责在数据库中维护唯一的主键(即 id)。它还验证主键的唯一性。但是,上面的代码正在尝试使用代码Artisan.create!(row.to_hash) 保存重复的“id”

您可以通过在创建过程中省略“id”属性来解决此问题。

 csv.each do |row|
   Artisan.create!(row.to_hash.except("id"))
 end

【讨论】:

  • 有效!谢谢你。这段代码以后不会有其他作用吧?就像我什么时候必须操纵 id 一样?
  • 最好不要使用“id”列在rails中存储任何用户定义的值。将 CSV 文件中的“id”列替换为其他内容。那么上面的代码就可以完美运行了。
  • 我认为每条语句都在我的后台造成了问题。每次我重新加载页面时,工匠都会重复
  • 你需要把你的代码放在一个方法中,只在需要的时候调用。在这种情况下,每次调用 Artisan 模型时,都会从 CSV 文件中提取记录。
  • 好的,我会尽力做到的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
相关资源
最近更新 更多