Rails 3,使用外键生成迁移

kal*_*elc 4 ruby-on-rails rails-migrations ruby-on-rails-3

我如何使用外键执行或生成迁移?我有municipios表,我想与表关联ciudades,表将有这些字段:( nombre_id名称ID),nombre(名称),departamento(部门)在这种情况下如何运行脚手架脚本来生成外键迁移?

ahm*_*hmy 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
Run Code Online (Sandbox Code Playgroud)

创建引用ciudades的municipios模型

rails g scaffold municipios ciudades:references
Run Code Online (Sandbox Code Playgroud)

这将在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
Run Code Online (Sandbox Code Playgroud)

同样在municipios模型上它将创建belongs_to关系.

但这不会更新cuidades模型.你必须指定关系.

另请注意,rails会自动在模型上创建id字段.这是惯例.如果你的意思是nombre_id是主键,你必须指定它自己.

希望这有帮助