Jonathan Jonathan - 8 months ago 46
Ruby Question

Rails adding reference to related models

I have the following setup to handle categories and sub categories.


class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged

has_many :subcategories
has_many :products ,:through => :subcategories


class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products


class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
belongs_to :subcategory

Do I need to add a category_id:integer & subcategory_id:integer to the products model make it work, or does Rails handle this for me automatically?


Yes, you need to add category_id and subcategory_id to your models migration file in order to make it work. Rails doesn't do it for you unless you're using rails generate syntax wisely. For eg. first you create Category model

rails generate model Category name:string

Then you create Subcategory model passing category as references.

rails generate model Subcategory name:string category:references

And then you create Product model passing subcategory as references

rails generate model Product name:string subcategory:references

This will automatically add category_id and subcategory_id to migration files. You will have to write the relations in your model yourself though(i.e., only the has_many part)

If you haven't done it by mistake you can create a new migration file and add reference yourself manually like the above answer suggested.