Dreams
Dreams

Reputation: 8506

How to validate in database for uniqueness?

I am using Rails 4.2 with Ruby 2.1.5.

Here is my API table:

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

How do I validate that a user cannot create an API with the same name and same status twice?

For example, (name)"ABC" with (status) "good" already exist and next time you cannot not create it again.

Upvotes: 0

Views: 80

Answers (3)

Zain Zafar
Zain Zafar

Reputation: 1607

You can ensure that in both model and migrationfile. I will suggest you to do this in both places but only model/migration will work too.

Note that applying restriction inside the model will provide you errors on the object.

In you migration file:

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

And in you model:

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

Upvotes: 0

caspg
caspg

Reputation: 399

You need to put this validation into you Api model:

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

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

Upvotes: 3

neuronaut
neuronaut

Reputation: 2709

You can use a unique index in the database and/or a uniqueness validation in the rails model class.

The unique index would be set up in a migration, like this:

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

And the validation would be something like this:

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

Upvotes: 3

Related Questions