Association problem

#1

What is the correct way to define one to many association in rails 5.we
have currently the following migration files…we have to define
products and categories tables such that one category has many products.

class Category < ApplicationRecord
has_many :products, dependent: :destroy
end

class Product < ApplicationRecord
belongs_to :category, index: true
end

#2

Those look like model definitions not migrations. It looks like you have them declared properly although I’m not sure about the ‘index: true’ on the 2nd declaration. I don’t see that in the Rails API for belongs_to.

#3

The corresponding migration might look like this:

class CreateCategories < ActiveRecord::Migration[5.2]
  def change
    create_table :categories do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateProducts < ActiveRecord::Migration[5.2]
 def change
    create_table :products do |t|
      t.string :name
      t.belongs_to :category, index: true
      t.timestamps
    end
  end
end

The corresponding model association might look like this:

class Category < ApplicationRecord
  has_many :products, dependent: :destroy
end

class Product < ApplicationRecord
  belongs_to :category
end