如何为唯一性验证表设置唯一索引



我已经将唯一性验证应用于"appeal_id";在名为";Campaigns";。它要求我添加一个唯一性索引以进行唯一性验证,我添加了campaign_id作为唯一性索引。但它仍然显示出同样的错误。

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 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我的活动表模式如下:

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";文件如下:

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

您缺少了确保两列组合唯一所需的复合索引。

添加它相对简单:

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

我删除了数据库,然后编辑了create_compaign迁移并添加了这行代码

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

在我的迁移中。然后运行命令

rails db:create db:migrate

它实际上再次创建了我的数据库,并解决了唯一索引的问题。

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

相关内容

  • 没有找到相关文章

最新更新