Search code examples
ruby-on-railsruby-on-rails-3rails-migrations

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 table 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?


Solution

  • 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