“Key (slug)=() already exists” in friendly_id on rails4 app

感情迁移 提交于 2019-12-25 04:40:46

问题


While I'm trying to setup friendly_id to my rails4 project, similarly, I got error after I add "friend" after "friend" to friends table. How can I fix it:

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

In addition, here are my files the issue may be based on:

# 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

UPDATE: migration file:

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

回答1:


Now fixed by uncommenting these lines on 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'

Thanks @basgys, @DavidGrayson and rest of us...




回答2:


The error makes it sound like two rows in the database share the same slug, which is just empty string, and that is not allowed because you are adding a unique index on the slug column.

When does the error actually happen? What keystroke or click causes it?

Either delete the rows in the friends table or make the index non-unique by removing that option from the migration file (you can change it later with another migration).



来源:https://stackoverflow.com/questions/19882054/key-slug-already-exists-in-friendly-id-on-rails4-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!