Rails 3, generate migration with foreign key
How I can do or generate a migration with a foreign key? I have municipios
table, and I want to relate with the t开发者_如何学JAVAable ciudades
, the table will have these fields: nombre_id
(name id), nombre
(name), departamento
(department) in this case how I can run the scaffold script to generate the foreign key migration?
If you mean that you want to create the migration file the command is
rails generate migration NAME [field:type field:type] [options]
or shortcut
rails g migration NAME [field:type field:type] [options]
But if you want to create a scaffold from model that referencing other model. Maybe you could do it like this
create ciudades model with scaffold
rails g scaffold ciudades nombre_id:integer nombre:integer departamento:string
create municipios model that reference ciudades
rails g scaffold municipios ciudades:references
this will create attribute ciudades_id on the municipios table. The migration should look like this.
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
also on the municipios model it will create the belongs_to
relation.
but this does not update the cuidades
model. You have to specify the relation.
Also keep in mind that rails automatically create id field on a model. it is the convention. if you mean that nombre_id is the primary key, you have to specify it your self.
Hope this help
Scaffold will not create the relationships for you. It will create views, controllers and others but the rest (relationships) need to be coded by hand.
So you scaffold "municipios", but if you want municipio has many ciudades, you need to do it yourself. For example:
When scaffold gives you:
<% form_for([@municipio]) do |f| %>
You need to change it to:
<% form_for([@municipio, @ciudad]) do |f| %>
精彩评论