如何使用外键执行或生成迁移?我有 municipios
表,我想与表相关联 ciudades
,该表将包含以下字段:nombre_id
(姓名 id), nombre
(姓名), departamento
(部门)在这种情况下我如何运行脚手架脚本来生成外键迁移?
最佳答案
如果您的意思是要创建迁移文件,则命令是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
创建引用 ciudades 的 municipios 模型
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
同样在 municipios 模型上,它将创建
belongs_to
关系。但这不会更新
cuidades
模型。您必须指定关系。还要记住,rails 会自动在模型上创建 id 字段。这是公约。如果你的意思是 nombre_id 是主键,你必须自己指定它。
希望这有帮助
关于ruby-on-rails - Rails 3,使用外键生成迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020029/