Topic: How to set up associations?

I'm looking for some guidance for a personal project of mine in RoR. I learned RoR using Michael Hartl's online book, and now I am building a different application for my own edification.

My web application will be similar to an e-commerce website, except instead of selling products, I'll be selling menu items from a restaurant. I have already implemented a users resource which stores basic information (name, email etc.), but I am seeking guidance on setting up the associations.

The restaurant 'show' page should display the restaurant name, a paragraph description of the restaurant, 3-5 photographs, a few descriptive tags, and a full menu with the dish names and prices. How should I attack this databasing problem? I am considering creating three models here, something like the following:

class Restaurant < ActiveRecord::Base
 has_many :dishes, :through => :menus
end

class Menu < ActiveRecord::Base
 belongs_to :restaurant
 has_many :dishes
end

class Dish < ActiveRecord::Base
 belongs_to :menu
 has_one :restaurant, :through => :menus
end

Is that about right? I'm new to relational databases so any tips would be helpful.

Last edited by Train (2012-04-04 21:09:48)

Re: How to set up associations?

Well, why do you need the menu model? Are restaurants going to be able to have multiple menus or will their be some information about a menu that you need to show?

I would simplify it to Restaurant and Dish. But you might want to pick a different name for dishes since it's plural form is abnormal with the "e", but maybe it works? How about Meal(s)?

Also, you mentioned you wanted tags for the restaurants. Tag would be another model you would have.

So, the relationship between restaurant and dish would look like this:

Restaurant
  has_many :dishes
  has_many :tags
Dish
  belongs_to :restaurant
Tag
  belongs_to :restaurant

Also, you might want to check out the acts-as-taggable-on gem, which makes it easy to add taggable attributes to a model. I also recommend Paperclip for the restaurant picture uploads. It's super easy to get working and integrates with imagemagick for image resizing.

Change is a vector. You can have all the change in the world, but if it doesn't go in the right direction, what good is it? | techonamission.com