2011-08-11 99 views
3

如何使用外鍵執行遷移或生成外鍵?我有municipios表,並且我想與表ciudades關聯,表中將包含以下字段:nombre_id(name id),​​(name),departamento(department)在這種情況下,我如何運行腳手架腳本來生成外鍵遷移?Rails 3,使用外鍵生成遷移

回答

5

如果你的意思是你要創建的遷移文件的命令是

rails generate migration NAME [field:type field:type] [options]

或快捷方式

rails g migration NAME [field:type field:type] [options]

但是,如果你想創建從引用了其他模型的模型支架。也許你可以做這樣的

創建腳手架ciudades模型

rails g scaffold ciudades nombre_id:integer nombre:integer departamento:string 

創建municipios模型引用ciudades

rails g scaffold municipios ciudades:references 

這將創建屬性上municipios表ciudades_id。 遷移應該看起來像這樣。

class CreateMunicipios < ActiveRecord::Migration 
    def self.up 
    create_table :municipios do |t| 
     t.references :ciudades 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :municipios 
    end 
end 

也在自治市模型它將創建belongs_to關係。

但這並不更新cuidades模型。你必須指定關係。

另外請記住,rails自動在模型上創建id字段。這是慣例。如果你的意思是nombre_id是主鍵,你必須指定它你的自我。

希望得到這個幫助

0

腳手架不會爲您創建關係。它將創建視圖,控制器和其他人,但其餘(關係)需要手工編碼。

所以你腳手架「municipios」,但如果你想municipio有很多ciudades,你需要自己動手。例如:

當支架爲您提供:

<% form_for([@municipio]) do |f| %> 

您需要將其更改爲:

<% form_for([@municipio, @ciudad]) do |f| %>