【问题标题】:How to validate in database for uniqueness?如何在数据库中验证唯一性?
【发布时间】:2015-06-16 16:45:54
【问题描述】:

我正在使用带有 Ruby 2.1.5 的 Rails 4.2。

这是我的 API 表:

create_table "apis", force: :cascade do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "status"
  t.string   "coname"
end

如何验证用户不能两次创建同名同状态的 API?

例如,(name)"ABC" 和 (status) "good" 已经存在,下次您不能再创建它。

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-4


    【解决方案1】:

    您需要将此验证放入您的 Api 模型中:

    validates :name, uniqueness: { scope: :status, message: 'your custom message' }

    http://guides.rubyonrails.org/active_record_validations.html#uniqueness

    【讨论】:

    • 和“它不会在数据库中创建唯一性约束,因此可能会发生两个不同的数据库连接为您打算唯一的列创建具有相同值的两条记录。为避免这种情况,您必须在数据库中的两列上创建唯一索引。"
    • 还有一个问题,我该如何设置不同的验证信息?
    【解决方案2】:

    您可以在数据库中使用唯一索引和/或在 rails 模型类中使用唯一性验证。

    唯一索引将在迁移中设置,如下所示:

    class AddUniqueIndexToApis < ActiveRecord::Migration
      add_index :apis, [:name, :status], unique: true
    end
    

    验证会是这样的:

    class Api < ActiveRecord::Model
      validates :name, uniqueness: { scope: :status }
    end
    

    【讨论】:

      【解决方案3】:

      您可以确保在 modelmigrationfile 中。我建议你在这两个地方都这样做,但只有模型/迁移也可以。

      请注意,在模型内应用限制将为您提供 对象上的错误。

      在您的迁移文件中:

      def change
        create_table "apis", force: :cascade do |t|
          t.string   "name"
          t.datetime "created_at"
          t.datetime "updated_at"
          t.string   "status"
          t.string   "coname"
       end
       add_index :name, :status, unique: true
      end
      

      在你的模型中:

      class ApiModel < ActiveRecord::Model
         validates :name, uniqueness: { scope: :status }
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-14
        相关资源
        最近更新 更多