Search code examples
ruby-on-railsactiverecordrails-migrations

Rails: How to setup multiple relation types to same models


I have a Product and Category model which have a has_and_belongs_to_many relation. So I can search for Product.categories or Category.products

class Product < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Category < ApplicationRecord
  has_and_belongs_to_many :products
end

Now I wanna add a new relation to the Product: It should called main_category which only should be a has_one relation from the Product to the Category. So a Product only can have one MainCategory. But the Category of course should return all MainCategory products.

  • Must I create a SubClass of Category? Normally I would like to not create an extra class

  • How can I solve that to simply call Product.main_category or Category.main_products?

  • How to place indexes properly?

  • How does the migration should look like?


Solution

  • You can simply do it like this i guess

    class Product < ApplicationRecord
         has_and_belongs_to_many :categories
         belongs_to :main_category, class_name: 'Category', foreign_key: :main_category_id
    end
    
    class Category < ApplicationRecord
         has_and_belongs_to_many :categories
         has_many :main_products, class_name: 'Product', foreign_key: :main_category_id
    end
    

    You will have to add an column to products table called main_category_id

    Source https://guides.rubyonrails.org/association_basics.html#bi-directional-associations