我在Rails上有这些模型:
class Tweet < ActiveRecord::Base
attr_accessible :status
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :tweets
end
但是在bd上这些模型之间没有关系。 我需要做哪些迁移才能将user_id添加到推文表中?
答案 0 :(得分:3)
您需要将user_id
添加到Tweet
模型中,然后在模型中添加:
运行rails g migration add_user_id_to_tweets user_id:integer
这将为您提供以下输出
class AddUserIdToTweet < ActiveRecord::Migration
def change
add_column :tweets, :user_id, :integer
end
end
答案 1 :(得分:2)
要运行迁移:
change_table :tweets do |t|
t.references :user
end
这将将名为user_id
的列添加到tweets
表中。 (不要忘记运行rake db:migrate
来更新数据库!)
Documentation of change_table
(ActiveRecord::ConnectionAdapters::SchemaStatements) - APIdock