Add Index to join table with unique checks

Ruby on Rails add index to join table, generate migration

1. make uniqueness index on areas_deals:
*This stops the association from being able to be duplicated, but throws an error causing bad UI, we will address that below**

//generate your migration
$ rails g migration AddIndexToAreasDeals

//Check and add to the migration

  class AddIndexToAreasDeals < ActiveRecord::Migration[5.0]
    def change
      add_index :areas_deals, [ :area_id, :deal_id ], :unique => true, :name => 'by_area_and_deal'

//once your migration looks right:
$ rake db:migrate

2. Check the schema and make sure you got what you want. We wanted this added:
t.index [“area_id”, “deal_id”], name: “by_area_and_deal”, unique: true

  create_table "areas_deals", force: :cascade do |t|
    t.integer  "area_id"
    t.integer  "deal_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "project_id"
    t.index ["area_id", "deal_id"], name: "by_area_and_deal", unique: true
    t.index ["area_id"], name: "index_areas_deals_on_area_id"
    t.index ["deal_id"], name: "index_areas_deals_on_deal_id"
    t.index ["project_id"], name: "index_areas_deals_on_project_id"

Add error exception to model to address uniqueness error

3. add error exception to the model to address the bad UI error spoken about above. We are just adding a message

class AreasDeal < ApplicationRecord
  belongs_to :project
  belongs_to :area
  belongs_to :deal
  validates_each :area_id, :on => [:create, :update] do |record, attr, value|
    c = value; p = record.deal_id
    if c && p && # If no values, then that problem 
                 # will be caught by another validator
      AreasDeal.find_by_area_id_and_deal_id(c, p)
      record.errors.add :base, 'This combination already exists'