Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder brad211987's Avatar
    Join Date
    Sep 2005
    Location
    Ohio
    Posts
    631
    Thanks
    10
    Thanked 50 Times in 50 Posts

    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.

  • #2
    New Coder
    Join Date
    May 2006
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •