如何在两个模型之间添加关系

时间:2013-05-29 21:07:53

标签: ruby-on-rails ruby

我在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添加到推文表中?

2 个答案:

答案 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

相关问题