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.
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.
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.
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.
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
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
Here is a great tutorial which shows two methods for using many_to_many relationships : http://railscasts.com/episodes/47-two-many-to-many
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With