add_column for references (Rails)

Ruby on-RailsSchema

Ruby on-Rails Problem Overview


I have the following Rails migration which works perfectly (irrelevant pieces removed):

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

Now I'd like to add an author column to my comments table (which is the userid of a user), but I have no idea how to do it (I'm tempted to just write the MySql-specific syntax using an execute).

I've been looking at add_column here which doesn't mention references. I've actually found TableDefinition#references but I have no idea how to use it with an add_column statement.

Is this possible? Also, is it true that, for MySql, the "references" functionality does not actually establish relationships between the tables?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

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

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

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

Solution 2 - Ruby on-Rails

add_reference :table_name, :reference, index: true

Solution 3 - Ruby on-Rails

Finally got it

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

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

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

Solution 6 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan RosenstarkView Question on Stackoverflow
Solution 1 - Ruby on-RailsJaime BellmyerView Answer on Stackoverflow
Solution 2 - Ruby on-RailsRajeev SharmaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSwapnil ChincholkarView Answer on Stackoverflow
Solution 4 - Ruby on-RailsMilan NovotaView Answer on Stackoverflow
Solution 5 - Ruby on-RailsCraig StuntzView Answer on Stackoverflow
Solution 6 - Ruby on-RailsmikeView Answer on Stackoverflow