Go Back   CodingForums.com > :: Server side development > Ruby & Ruby On Rails

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-06-2008, 07:09 PM   PM User | #1
brad211987
Regular Coder

 
brad211987's Avatar
 
Join Date: Sep 2005
Location: Ohio
Posts: 631
Thanks: 10
Thanked 50 Times in 50 Posts
brad211987 is an unknown quantity at this point
Many to Many relationship

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:
Code:
@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.
brad211987 is offline   Reply With Quote
Old 05-31-2008, 12:48 AM   PM User | #2
JamieD
New Coder

 
Join Date: May 2006
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
JamieD is an unknown quantity at this point
Hi,

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

Jamie
__________________
Flexible UK web hosting solutions for designers and developers
PHP5, Ruby on Rails, MySQL, spam and virus filtering
UK Hosting from Media72, Media72 on twitter
JamieD is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:19 AM.


Advertisement
Log in to turn off these ads.