【问题标题】:Why did Rails ignore my user_id field?为什么 Rails 忽略了我的 user_id 字段?
【发布时间】:2010-09-19 21:51:55
【问题描述】:

我尝试在 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 列。发生了什么事,这里?

【问题讨论】:

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


    【解决方案1】:

    因为它应该是t.integer,而不是t.int。见docs for more details:

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

    【讨论】:

    • 该死,我有一种感觉会这么简单。谢谢! (我会在 10 分钟内接受这个答案。)
    • 这一直困扰着我。为什么迁移不会引发无效列类型的异常?
    【解决方案2】:

    你也可以使用:

    t.references :user
    

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

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2011-12-31
      • 2021-05-21
      • 1970-01-01
      相关资源
      最近更新 更多