I added a has_and_belongs_to_many between Product and Brand tables/models
This is how the models look like:
class Brand < ActiveRecord::Base
has_and_belongs_to_many :products
default_scope { order('name asc')}
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :brands
end
These are the existing columns in the table:
[13] pry(main)> Brand
=> Brand(id: integer, name: string, created_at: datetime, updated_at: datetime, product_id: integer)
[11] pry(main)> Product
=> Product(id: integer, name: string, created_at: datetime, updated_at: datetime)
Join table db migration:
class CreateJoinTableProductsBrands < ActiveRecord::Migration
def change
create_join_table :products, :brands do |t|
t.integer :product_id
t.integer :brand_id
t.index [:product_id, :brand_id]
t.index [:brand_id, :product_id]
end
end
end
Questions:
- As you will notice, the Brand table already had the product_id column. Should I change it to an array product_ids column? (I am using postgres)
- Should I add brand_ids column to Product
Should I add ProductBrand model. I tried it but seems like Rails console didnt recognize it
class ProductBrand < ActiveRecord::Base
end
In ActiveAdmin what's the correct way of creating a new entry for Product or Brand such that a new record correctly links Product, Brand and ProductBrand entry?