0

So imagine a situation where you have many meals. You can then categorize these meals as you see fit. So the two objects would be

class Category < ActiveRecord::Base
  attr_accessible :name
  has_many :meal
end

class Meal < ActiveRecord::Base
  attr_accessible :name
  has_and_belongs_to_many :category
end

So categories don't really belong to a meal, but meals can belong to many categories.

Is this incorrect? Should category have has_and_belongs_to_many instead? Or should this relationship be a has_many, :through one?

justindao
  • 2,273
  • 4
  • 18
  • 34
  • you will need a intermediate table to store all the meal and category connections. Checkout more on rails guide how to do that: http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association – Zippie Jun 06 '13 at 19:33
  • I know, but will the models be as stated above, or will I need to change one or both of them? – justindao Jun 06 '13 at 19:35
  • 1
    Both models will need to have a `has_and_belongs_to_many relationship`, since one meal will reference many categories and one category will reference many meals. – Zippie Jun 06 '13 at 19:37
  • I thought as much. It's just a little confusing, since categories don't really "belong to" a meal. – justindao Jun 06 '13 at 19:39
  • I understand, but try to write it on a paper and you will see why it won't work :) – Zippie Jun 06 '13 at 19:41

0 Answers0