[ACCEPTED]-add_column for references (Rails)-schema
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
end
end
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.
add_reference :table_name, :reference, index: true
0
Finally got it
add_column :locations, :state_id , :integer, :references => "states"
0
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"
end
class Comment
belongs_to :author, :class_name => User
end
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.
You could add the column by add_column(:table, :column_name, :type, :options)
in a new Migration.
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.