Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

schema - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...