Reputation: 18541
I have two objects i.e. recipe & ingredient.
I have created them using
rails generate scaffold ingredient id:integer name:string
rails generate scaffold recipe id:integer name:string
I want too create them with a n:m relation (many-to-many).
How do I do it? Should I create a different scaffold?
Thanks.
Upvotes: 7
Views: 9790
Reputation: 39458
You can execute rails generate migration create_join_table_ingredient_recipe ingredient recipe
which will generate a migrations file, which you can modify to include indices and foreign keys, like:
class CreateJoinTableIngredientRecipe < ActiveRecord::Migration
def change
create_join_table :ingredients, :recipes do |t|
t.index [:ingredient_id, :recipe_id]
t.index [:recipe_id, :ingredient_id]
end
add_foreign_key :ingredients_recipes, :ingredients
add_foreign_key :ingredients_recipes, :recipes
end
end
Then you can add in models/ingredient.rb
:
has_and_belongs_to_many :recipe
and conversely in models/recipe.rb
:
has_and_belongs_to_many :ingredients
Upvotes: 7
Reputation: 9691
Here is a great tutorial which shows two methods for using many_to_many relationships : http://railscasts.com/episodes/47-two-many-to-many
Upvotes: 5
Reputation: 13925
No, you need to create a join table, by generatin a migration.
rails g migration ingredients_recipes ingredient_id:integer recipient_id:integer
Then, you can add to your models:
Ingredient.rb
has_and_belongs_to_many :recipe
Recipe.rb
has_and_belongs_to_many :ingredients
Or if you want to add other properties to the connection (e.g. Quantity), then you may generate a model for it.
rails g model ingredients_recipes ingredient_id:integer recipient_id:integer
Upvotes: 12