0

我尝试在 Rails 中创建一个如下所示的数据库迁移:

ruby 脚本/生成脚手架帖子 user_id:int 标题:字符串内容:文本

查看生成的 .rb 文件,果然,我看到了我输入的所有内容:

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.int :user_id # there it is: user_id
      t.string :title
      t.text :content

      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

但是在运行rake db:migrate并检查了我的数据库之后,我发现没有user_id创建任何列。这里发生了什么?

4

2 回答 2

3

您还可以使用:

t.references :user

它将创建一个名为 user_id 的整数字段。我个人更喜欢这种方法,因为它引用了外键。

于 2010-09-20T00:12:23.257 回答
3

因为应该t.integer,不是t.int。有关更多详细信息,请参阅文档

add_column(table_name, column_name, type, options)table_name: 向表中添加一个名为named的新列,column_name指定为下列类型之一::string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

于 2010-09-19T21:53:54.687 回答