前提
初学者です!
いいね機能を持ったアプリを作っており、自動レビュー課題にてRails/UniqueValidationWithoutIndex: Uniqueness validation should be with a unique index.
というようなエラーが出ています。
エラー修正のためにschema.rbについて少しお聞きしたいのですが。。。
実現したいこと
schema.rbの該当部分に以下の3文を追加したいのですが、この場合は新たなマイグレーションファイルを作ってrails db:migrate
を実行しないとダメでしょうか?
t.index ["post_id"], name: "index_likes_on_post_id" t.index ["user_id", "post_id"], name: "index_likes_on_user_id_and_post_id", unique: true t.index ["user_id"], name: "index_likes_on_user_id"
該当のソースコード
# schema.rb(該当部分) create_table "likes", force: :cascade do |t| t.integer "user_id" t.integer "post_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
# like.rb class Like < ApplicationRecord belongs_to :user belongs_to :post validates :post_id, uniqueness: { scope: :user_id } end
# _create_likes.rb class CreateLikes < ActiveRecord::Migration[5.2] def change create_table :likes do |t| t.integer :user_id, null: false, foreign_key: true t.integer :post_id, null: false, foreign_key: true t.timestamps end add_index :likes, [:user_id, :post_id], unique: true end end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。