为什么Rails会忽略我的user_id字段?

时间:2010-09-19 21:51:55

标签: ruby-on-rails activerecord migration rake reserved-words

我尝试在Rails中创建一个类似于这样的数据库迁移:

ruby script/generate scaffold post user_id:int title:string content:text

查看生成的.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列。发生了什么,这里?

2 个答案:

答案 0 :(得分:3)

因为它应该是t.integer,而不是t.int。请参阅docs for more details

  

add_column(table_name, column_name, type, options):在名为table_name的名为column_name的表中添加一个新列,指定为以下类型之一::string:text,{ {1}},:integer:float:decimal:datetime:timestamp:time:date,{{1 }}

答案 1 :(得分:3)

您也可以使用:

t.references :user

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