Add_column for links (Rails)

I have the following Rails migration that works fine (irrelevant fragments removed):

create_table :comments do |t| t.text :body t.references :post end 

Now I would like to add the author column to my comments table (which is the user ID), but I have no idea how to do this (I am tempted to just write MySql-specific syntax using execute ).

I looked at add_column here which does not mention references . I actually found a TableDefinition # link , but I have no idea how to use it with the add_column .

Is it possible? Is it also true that for MySql, the functionality of β€œlinks” does not actually establish relationships between tables?

+54
ruby-on-rails schema
Jan 29 '09 at 10:30
source share
6 answers

While it is too late to get any points from this, I thought I would put the best way for posterity :)

use change_table instead of create_table to add columns to a table that already exists, with all the benefits of TableDefinition:

 self.up do change_table :comments do |t| t.references :author end end 

This may seem trivial, but other gems, such as Devise, make heavy use of their own custom table definitions, and so you can still use them.

+99
Oct. 15 '10 at 18:21
source share
 add_reference :table_name, :reference, index: true 
+61
Jan 07 '14 at 19:25
source share

Finally he got

 add_column :locations, :state_id , :integer, :references => "states" 
+34
Apr 21 '11 at 10:12
source share

First, do:

 script/generate migration AddAuthorIdToComments 

Open the generated file and add this line:

 add_column :comments, :author_id, :integer 

Then in your model files:

 class User < ActiveRecord::Base has_many :comments, :foreign_key => "author_id" end class Comment belongs_to :author, :class_name => User end 
+20
Jan 29 '09 at 22:39
source share

It has been some time since I looked at this, but the last time I checked the migration did not support the creation of foreign keys. Fortunately, however, there is a plugin for it . I used this and it works well.

+2
Jan 29 '09 at 22:43
source share

You can add the add_column(:table, :column_name, :type, :options) column add_column(:table, :column_name, :type, :options) to the new migration.

0
Jan 29 '09 at 22:34
source share



All Articles