Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - n:m many-to-many relation

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.

like image 769
Bick Avatar asked Apr 27 '12 13:04

Bick


People also ask

Has many to has many relationship Rails?

Many-to-many is one of the most common relationship in Rails(database). The concept is simple. When both 2 models have has_many association to each other, we say they are many-to-many relationship.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What has and belongs to many or has many through?

Stories can belong to many categories. Categories can have many stories. has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models. Person can subscribe to many magazines.


3 Answers

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
like image 55
Matzi Avatar answered Oct 09 '22 19:10

Matzi


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
like image 25
mb21 Avatar answered Oct 09 '22 18:10

mb21


Here is a great tutorial which shows two methods for using many_to_many relationships : http://railscasts.com/episodes/47-two-many-to-many

like image 29
gabitzish Avatar answered Oct 09 '22 18:10

gabitzish