Home > Mobile >  How to set unique index for uniqueness validation table?
How to set unique index for uniqueness validation table?

Time:10-03

I've applied uniqueness validation to "appeal_id" in model named "Campaigns". It asks me to add a unique index for uniqueness validation, I added campaign_id as a unique index. But it still shows the same error.

app/models/campaign.rb:9:3: C: Rails/UniqueValidationWithoutIndex: Uniqueness validation should have a unique index on the database column.
  validates :appeal_id, uniqueness: { scope: :user_id }
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

My schema for campaigns table looks like following:

create_table "campaigns", force: :cascade do |t|
        t.string "title"
        t.text "description"
        t.bigint "appeal_id", null: false
        t.bigint "user_id", null: false
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer "campaign_id"
        t.index ["appeal_id"], name: "index_campaigns_on_appeal_id"
        t.index ["campaign_id"], name: "index_campaigns_on_campaign_id", unique: true
        t.index ["user_id"], name: "index_campaigns_on_user_id"
      end

"campaign.rb" file is as follows:

class Campaign < ApplicationRecord
  has_many :donations, dependent: :destroy
  belongs_to :appeal
  belongs_to :user
  validates :title, presence: true
  validates :description, presence: true
  validates :appeal_id, uniqueness: { scope: :user_id }
end

CodePudding user response:

You're missing the compound index that you actually need to ensure that the combination of the two columns is unique.

Adding it is relatively simple:

class AddUniqueCompoundIndexToCampaigns < ActiveRecord::Migration[7.0]
  def change
    add_index [:appeal_id, :user_id], unique: true
  end
end

CodePudding user response:

I dropped my database and then edited my create_campaign migration and added this line of code

add_index :campaigns, [:appeal_id, :user_id], unique: true

in my migration. Then run the command

rails db:create db:migrate

which actually created my database again and resolved the issue of unique index.

class CreateCampaigns < ActiveRecord::Migration[7.0]
  def change
    create_table :campaigns do |t|
      t.string :title
      t.text :description
      t.references :appeal, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
    add_index :campaigns, [:appeal_id, :user_id], unique: true
  end
end
  • Related