2012-04-27 120 views
4

我有兩個對象,即配方&成分。
我一直在使用Ruby on Rails - n:m多對多關係

rails generate scaffold ingredient id:integer name:string 
rails generate scaffold recipe id:integer name:string 

我想太多了N新建他們創造他們:M關係(很多到很多)。
我該怎麼做?我應該創建一個不同的腳手架嗎? 謝謝。

回答

9

不,您需要創建一個連接表,通過生成一個遷移。

rails g migration ingredients_recipes ingredient_id:integer recipient_id:integer 

然後,您可以添加到您的模型:

Ingredient.rb

has_and_belongs_to_many :recipe 

Recipe.rb

has_and_belongs_to_many :ingredients 

或者,如果要添加其他屬性的連接(例如數量),那麼你可以爲它生成一個模型。

rails g model ingredients_recipes ingredient_id:integer recipient_id:integer 
+0

是有辦法的時候我已經創建了最初的支架做呢? – Jeb 2012-04-27 15:00:21

+0

它創建了一個空的rb文件,只包含 - def up end def down end。 – Jeb 2012-04-27 15:27:22

4

可以執行rails generate migration create_join_table_ingredient_recipe ingredient recipe,這將產生一個遷移文件,您可以修改包括索引和外鍵,如:

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 

然後你就可以添加在models/ingredient.rb

has_and_belongs_to_many :recipe 

反之:

has_and_belongs_to_many :ingredients