ruby-on-railsruby-on-rails-4.2

How to add column as foreign key with cascade delete in rails


I have two table one product and another usage

Product
#  id                  :integer          not null, primary key
#  product_name        :string           not null
#  plan_id             :string
#  plan_name           :string

Usage
#  id              :integer          not null, primary key
#  quantity        :float
#  date            :date

Want to add product_id as foreign key in usage

i am trying to run migration

 def change
    add_reference(:usages, :products, foreign_key: { on_delete: :cascade })
 end

Getting error column "product_id" referenced in foreign key constraint does not exist


Solution

  • Solution is ref_name should be singular

     add_reference(:usages, :product, foreign_key: { on_delete: :cascade })