Migraciones de Rails 3: ¿Añadiendo columna de referencia?


Si creo una nueva migración de rails 3 con (por ejemplo)

rails g migration tester title:tester user:references

, todo funciona bien...sin embargo, si agrego una columna con algo parecido a:

rails g migration add_user_to_tester user:references

No se reconoce el campo de referencia. En resumen, la pregunta es: ¿cómo puedo añadir una columna de referencia a una migración de rails desde la línea de comandos?

Author: Simone Carletti, 2011-02-10

10 answers

Si está utilizando los Rails 4.x ahora puede generar migraciones con referencias, así:

rails generate migration AddUserRefToProducts user:references

Como se puede ver en guías de carriles

 203
Author: Paulo Fidalgo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-29 13:55:28

EDITAR : Esta es una respuesta obsoleta y no debería aplicarse para Rails 4.x +

No necesita agregar referencias cuando puede usar un id de entero a su clase referenciada.

Diría que la ventaja de usar referencias en lugar de un entero simple es que el modelo estará predefinido con belongs_to y como el modelo ya está creado y no se verá afectado cuando migre algo existente, el propósito se pierde.

Así que me gustaría esto en cambio:

rails g migration add_user_id_to_tester user_id:integer

Y luego agregar manualmente belongs_to: user en el modelo de probador

 186
Author: DanneManne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-04 06:29:37

Tenga en cuenta que lo más probable es que también necesite un índice en esa columna.

class AddUserReferenceToTester < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
    add_index  :testers, :user_id
  end
end
 101
Author: Eugene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-10 21:54:01

Con los dos pasos anteriores mencionados anteriormente, todavía le falta la restricción de clave foránea. Esto debería funcionar:

  class AddUserReferenceToTester < ActiveRecord::Migration
      def change
          add_column :testers, :user_id, :integer, references: :users
      end
  end
 50
Author: Martin Cabrera Diaubalick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-30 16:04:38

Usted puede usar referencias en una migración de cambios. Este es el código válido de Rails 3.2.13:

class AddUserToTester < ActiveRecord::Migration
  def change
    change_table :testers do |t|
      t.references :user, index: true 
    end
  end
  def down
    change_table :testers do |t|
      t.remove :user_id
    end
  end
end

C. f.: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table

 35
Author: gl03,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-26 12:45:37

Ejecutando rails g migration AddUserRefToSponsors user:references generará la siguiente migración:

def change
  add_reference :sponsors, :user, index: true
end
 27
Author: Wirwing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-10 21:52:30

Al agregar una columna, debe hacer que esa columna sea un entero y, si es posible, seguir las convenciones de rails. Así que para su caso estoy asumiendo que ya tiene un Probador y modelos de usuario, y probadores y tablas de usuarios.

Para agregar la clave foránea necesita crear una columna entera con el nombre user_id (convention):

add_column :tester, :user_id, :integer

Luego agregue un belongs_to al modelo del probador:

class Tester < ActiveRecord::Base
  belongs_to :user
end

Y es posible que también desee agregar un índice para la clave foránea (esto es algo que las referencias ya lo hace por ti):

add_index :tester, :user_id
 8
Author: Zamith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-03 12:58:24

Eso hará el truco:

rails g migration add_user_to_tester user_id:integer:index
 8
Author: masterweily,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 10:06:24

Puede agregar referencias a su modelo a través de la línea de comandos de la siguiente manera:

rails g migration add_column_to_tester user_id:integer

Esto generará un archivo de migración como :

class AddColumnToTesters < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
  end
end

Esto funciona bien cada vez que lo uso..

 3
Author: Neha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-29 08:54:19

Para los carriles 4

El generador acepta el tipo de columna como referencias (también disponible como belongs_to).

Esta migración creará una columna user_id e índice apropiado:

$ rails g migration AddUserRefToProducts user:references 

Genera:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end

Http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

Para los carriles 3

El Helper se llama referencias (también disponible como belongs_to).

Esta migración cree una columna category_id del tipo apropiado. Tenga en cuenta que pasa el nombre del modelo, no el nombre de la columna. Active Record agrega el _id para usted.

change_table :products do |t|
  t.references :category
end

Si tiene asociaciones polimórficas belongs_to entonces las referencias agregarán ambas columnas requeridas:

change_table :products do |t|
  t.references :attachment, :polymorphic => {:default => 'Photo'}
end

Agregará una columna attachment_id y una columna string attachment_type con un valor predeterminado de Photo.

Http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration

 3
Author: shilovk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-13 10:58:12