has_many etc

I've got myself quite mixed up on has_many and related issues.

Suppose I have a lot of Recipes, each of which is to have many Ingredients.

I think I am meant to do e.g. models/recipe.rb

  class Recipe < ActiveRecord::Base     has_many :ingredients   end

along with models/ingredient.rb

  class Ingredient < ActiveRecord::Base     belongs_to :recipe   end

Is that right, with the has_many and belongs_to, with the plurality and use of upper and lower case?

Now I come to my real confusion. I half-think I should create a model "Recipes_Ingredients", but I'm not sure on that, so I've not done it.

What I *have* done is to create a table in one of my migrations, viz

  class RecipesIngredients < ActiveRecord::Migration     def self.up       create_table :recipes_ingredients, :id => false do |t|         t.column :ingredient_id, :integer         t.column :recipe_id, :integer       end       add_index :recipes_ingredients, [:ingredient_id, :recipe_id]       add_index :recipes_ingredients, :recipe_id    end    def self.down      drop_table :recipes_ingredients    end end

but is this enough? Am I supposed to use "execute" lines to make up foreign keys, or will this do what I need?

I think that what I've done is insufficient, because no method   recipe.ingredient seems to have been created. (Hm... is there a way to make the system describe the methods it's creating, during migration and otherwise?)

PS. I note that the Roll-With Revisited tutorial http://www.onlamp.com/ pub/a/onlamp/2006/12/14/revisiting-ruby-on-rails-revisited.html? page=2 illustrates the use of MYSQL code

  constraint fk_recipes_categories foreign key (category_id) references categories(id), primary key(id)

but I'm hoping to avoid hand injection of MySQL. (If I wanted to work with MySQL directly, I'd be back with PHP!)

Well, I hope I've been clear. As readers may guess, I'm not really working on recipes and ingredients, so I hope I've done tthe conversion to these more evocative names correctly enough that my point is clear.

PS. I'm using the new RoR, with MySQL.

this article should get you going Dan - funny enough it's on subject too!

http://blog.hasmanythrough.com/2006/3/28/the-other-ways-through

Cheers, Jodi General Partner The nNovation Group inc. www.nnovation.ca/blog

on-innovation.gif

(Answer to own question.)

I realized that models/ingredients.rb needs

  has_and_belongs_to_many :recipes

and that models/recipes.rb needs

  has_and_belongs_to_many :ingredients

to get the desired effect.

PS to Jodi -- that's a very informative site you pointed out; thanks very much.