View Full Version : Many to Many relationship

01-06-2008, 07:09 PM
I'm working on an application to get myself familiar with Ruby on Rails. My application manages a recipe book and will allow the user to store everything about recipes in a database(ingredients, instructions etc..). My problem is how to manage the database from Ruby on Rails. The relationship in question is between a recipe and an ingredient.

What I wanted to do, is set up an ingredient as its own entity and let it be added to a recipe using check boxes or something along those lines, so this requires a many-to-many relationship between recipes and ingredients. So far thats not really a problem, but I wanted to store quantities and units of measure with it. The database layout I wanted is to have a recipe table, and an ingredients table, then in the recipes_ingredients cross reference table, I would like to have the recipe ID, and Ingredient ID like normal, but also store quantity and unit_of_measure in the same table.

I'm sure I can simply add the fields to the database table, but how would I account for this inside of the Ruby on Rails application? I should be able to connect them and access a particular ingredient with something like:

@recipe.ingredients[1]My other option is to store the quantity and unit of measure inside the ingredient table, which would work fine and would change the relationship to a many-to-one, but I thought this way would be better and easier to understand as far as the database layout goes.

05-31-2008, 12:48 AM

You want to look at has_many :through associations, this does exactly what you need. See http://wiki.rubyonrails.org/rails/pages/Beginner+Howto+on+has_many+:through for how to use them.