[ACCEPTED]-add_column for references (Rails)-schema

Accepted answer
Score: 116

While it's too late to get any points out 8 of this, I thought I'd post the best way 7 for posterity :)

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

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

This might 4 seem trivial, but other gems like Devise 3 make heavy use of their own custom table 2 definitions, and this way you can still 1 use them.

Score: 98
add_reference :table_name, :reference, index: true


Score: 39

Finally got it

add_column :locations, :state_id , :integer, :references => "states"


Score: 22

First, do:

script/generate migration AddAuthorIdToComments

Open the generated file and add 1 this line:

add_column :comments, :author_id, :integer

Then in your model files:

class User < ActiveRecord::Base
  has_many :comments, :foreign_key => "author_id"

class Comment
  belongs_to :author, :class_name => User
Score: 2

It's been a while since I've looked at this, but 3 last I checked migrations don't support 2 creating foreign keys. Fortunately, however, there is a plug-in for it. I've 1 used this and it works well.

Score: 0

You could add the column by add_column(:table, :column_name, :type, :options) in a new Migration.


More Related questions