“key(slug)=()已经存在”在rails4 app上的friendly_id中

虽然我正在尝试将friendly_id设置为我的rails4项目,但同样地 ,我在“朋友”之后将“朋友”添加到friends表后出错。 我该如何解决它:

  PG::UniqueViolation - ERROR: duplicate key value violates unique constraint "index_friends_on_slug" DETAIL: Key (slug)=() already exists. 

另外,以下是我的文件问题可能基于:

 # app/models/friend.rb: class Friend < ActiveRecord::Base has_many :entries, dependent: :destroy belongs_to :user extend FriendlyId friendly_id :candidates, use: [:slugged, :finders] # not :history here def candidates [ :first_name, [:first_name, :last_name] ] end end # db/schema.rb: create_table "friends", force: true do |t| t.string "first_name" t.string "last_name" t.text "address" t.string "email" t.string "phone" t.string "slug" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "friends", ["slug"], name: "index_friends_on_slug", unique: true, using: :btree add_index "friends", ["user_id"], name: "index_friends_on_user_id", using: :btree 

更新:迁移文件:

 class CreateFriends < ActiveRecord::Migration def change create_table :friends do |t| t.string :first_name t.string :last_name t.text :address t.string :email t.string :phone t.string :slug t.integer :user_id t.timestamps end add_index :friends, :slug, unique: true add_index :friends, :user_id end end 

现在通过在config/initializers/friendly_id.rb上取消注释这些行来修复:

  # Most applications will use the :slugged module everywhere. If you wish # to do so, uncomment the following line. # config.use :slugged, :finders # # By default, FriendlyId's :slugged addon expects the slug column to be named # 'slug', but you can change it if you wish. # config.slug_column = 'slug' 

谢谢@basgys,@ DavidGrayson和我们其他人……

该错误使得它听起来像数据库中的两行共享相同的slug,这只是空字符串,并且这是不允许的,因为您在slug列上添加了唯一索引。

错误何时实际发生? 什么击键或点击导致它?

删除friends表中的行或通过从迁移文件中删除该选项使索引非唯一(您可以稍后通过其他迁移更改它)。