Rails 5:Rails URL错误的自定义标记

时间:2019-02-04 10:14:16

标签: ruby-on-rails

我一直在遵循hackernoon上的教程,以生成混淆的URL。

第一步是向数据库中添加一个子弹列,但出现错误。

AddSlugToReservations

class AddSlugToReservation < ActiveRecord::Migration[5.2]
  def change
    add_column :reservations, :slug, :string, null: false
    add_index :reservations, :slug, unique: true
  end
end

尝试rails db:migrate

时出现以下错误
SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "reservations" ADD "slug" varchar NOT NULL

所以我将迁移文件更改为:

class AddSlugToReservation < ActiveRecord::Migration[5.2]
  def change
    add_column :reservations, :slug, :string, null: false, default: 0
    change_column :reservations, :slug, :string, default: nil
    add_index :reservations, :slug, unique: true
  end
end

但是后来我遇到了以下错误:

SQLite3::ConstraintException: UNIQUE constraint failed: reservations.slug: CREATE UNIQUE INDEX "index_reservations_on_slug" ON "reservations" ("slug")

我该怎么办?我找不到任何解决方案...

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码进行操作

class AddSlugToReservation < ActiveRecord::Migration[5.0]
  def change
    add_column :reservations, :slug, :string, unique: true, default: 0, null: false
  end
end

答案 1 :(得分:0)

尝试

class AddSlugToReservation < ActiveRecord::Migration[5.2]
  def change
    add_column :reservations, :slug, :string, unique: true
    change_column_null :reservations, :slug, false
  end
end

希望有帮助。