0

My website has Category->Subcategory->Gigs (by gigs i mean lots of adds)

Below are the relationships between the 3 models.

class Category < ActiveRecord::Base
  has_many :subcategories
end


class Subcategory < ActiveRecord::Base
  belongs_to :category
  has_many :gigs
end


class Gig < ActiveRecord::Base
  belongs_to :user
  belongs_to :subcategory
end

Question:

What rails migrations should i use to make the required relationship between them in schema.rb,for example ("should i create category_id,or subcategory_id,or gig_id...),if yes in what table should they go,i got quite confused about it.

Thank you for your time.

1 Answer 1

2

A "belongs_to" relationship always requires a foreign key on that table.

With that being said, your gigs table should have

t.integer :user_id
t.integer :subcategory_id

and your subcategories table should have

t.integer :category_id

hope that helps!

2
  • After i created all the Categories,and subcategories names,for example Car Main category,how do i link it to window,tax,road,tyre subcategories? Apr 3, 2015 at 12:09
  • 1
    assuming that you have car_main = Category.create(:name => "Car Main") when you set up a subcategory, you can build it with the category set to the car_main variable: window = Subcategory.create(:name => "window", :category => car_main)
    – Snags88
    Apr 3, 2015 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.