0

当我尝试设置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
4

2 回答 2

2

现在通过取消注释这些行来修复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 和我们其他人......

于 2013-11-10T18:34:25.777 回答
0

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

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

要么删除朋友表中的行,要么通过从迁移文件中删除该选项使索引不唯一(您可以稍后通过另一个迁移更改它)。

于 2013-11-10T18:17:06.417 回答