我在看外國人的寶石,並試圖創建一些外鍵。然而,寶石documentation說,你應該像`add_foreign_key(from_table,to_table,options)一樣創建你的外鍵,但是當我這樣做時,它看起來像是倒退了。例如,我有3個模型,Entry,Ingredient和一個名爲EntryIngredient的關聯。通過EntryIngredient進入許多成分,成分通過EntryIngredients進行許多輸入,並且EntryIngredient屬於這兩者。然而,這是工作的代碼:外國人的寶石是如何工作的?
class EntryIngredient < ActiveRecord::Base
belongs_to :entry
belongs_to :ingredient
end
class CreateEntryIngredients < ActiveRecord::Migration
def self.up
create_table :entry_ingredients do |t|
t.references :entry
t.references :ingredient
t.integer :quantity
t.string :unit
t.timestamps
end
add_index :entry_ingredients, [:entry_id, :ingredient_id]
add_foreign_key :entry_ingredients, :entries, :dependent => :delete
add_foreign_key :entry_ingredients, :ingredients, :dependent => :delete
end
def self.down
drop_table :entry_ingredients
end
end
通過我認爲,外鍵實際上應該這樣添加的文檔:
add_foreign_key :entries, :entry_ingredients, :dependent => :delete
add_foreign_key :ingredients, :entry_ingredients, :dependent => :delete
但是當我運行遷移,返回了我
Mysql2::Error: Key column 'entry_ingredient_id' doesn't exist in table: ALTER TABLE `entries` ADD CONSTRAINT `entries_entry_ingredient_id_fk` FOREIGN KEY (`entry_ingredient_id`) REFERENCES `entry_ingredient`(id) ON DELETE CASCADE
有人可以向我解釋這裏發生了什麼?我爲什麼是誦讀困難?