【问题标题】:"Key (slug)=() already exists" in friendly_id on rails4 apprails4 应用程序上的friendly_id 中的“密钥(slug)=()已经存在”
【发布时间】:2013-11-09 19:24:12
【问题描述】:

当我尝试将friendly_id 设置到我的rails4 项目similarly 时,在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

【问题讨论】:

  • 你能告诉我们你的迁移吗?
  • @basgys 问题已更新。

标签: ruby-on-rails ruby-on-rails-4 friendly-id


【解决方案1】:

现在通过取消注释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 和我们其他人...

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2016-04-03
      • 1970-01-01
      相关资源
      最近更新 更多