Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add_column for references (Rails)

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?

like image 575
Dan Rosenstark Avatar asked Jan 29 '09 22:01

Dan Rosenstark


People also ask

How do I add a reference column in Rails?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

Do you need foreign keys in Rails?

You do not need a foreign key constraints for ActiveRecord to correctly map the relationships. You can use validations to have the Rails app ensure data integrity.

What is schema RB in Rails?

The schema. rb serves mainly two purposes: It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.


1 Answers

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.

like image 125
Jaime Bellmyer Avatar answered Sep 21 '22 08:09

Jaime Bellmyer