Rails SQL3唯一性验证失败

时间:2019-01-19 02:49:24

标签: sql ruby-on-rails

我在一个网站上工作,并且创建了一个迁移文件,以使项目的名称属性唯一。我添加了验证以检查唯一性,但是我所有的测试都导致“ ActiveRecord :: RecordNotUnique:SQLite3 :: ConstraintException:UNIQUE约束失败”。

这是我的迁移文件

class AddIndexToProduct < ActiveRecord::Migration[5.1]
  def change
    add_index :products, :name, unique: true
  end
end

class CreateProducts < ActiveRecord::Migration[5.1]
  def change
    create_table :products do |t|
      t.string :name
      t.float :price
      t.integer :inventory

      t.timestamps
    end
  end
end

这是我的验证

  validates :name, presence: true, length: {maximum: 15}, uniqueness: {case_sensitive: false}
  validates :price, presence: true, length: {maximum: 15}
  validates :price, presence: true, numericality: {only_float: true, greater_than: 0, less_than: 10000}
  validates :inventory, presence: true, numericality: {only_integer: true, greater_than: 0, less_than: 10000}

这是我的模型测试

  def setup
    @product = Product.new(name: "Bannana", price: 1.96, inventory: 3)
  end

  test "valid product" do
    assert @product.valid?
  end

  test "products should be unique" do
    duplicate_product = @product.dup
    duplicate_product.name = @product.name.upcase
    @product.save
    assert_not duplicate_product.valid?
  end

  test "check if we can add a product with a negative price or zero" do
    @product.price = -20
    assert_not @product.valid?
    @product.price = 0
    assert_not @product.valid?
  end

  test "check if we can add a product without a name, price, or quantity" do
    @product.name = "     "
    assert_not @product.valid?
    @product.price = nil
    assert_not @product.valid?
    @product.inventory = nil
    assert_not @product.valid?
  end

  test "check if name is too long" do
    @product.name = "This name for a product is way too long for meeeee"
    assert_not @product.valid?
  end

0 个答案:

没有答案