为什么 Rails 忽略我的 user_id 字段?
我尝试在 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
列。这里发生了什么事?
I tried creating a DB migration in Rails that looked something like this:
ruby script/generate scaffold post user_id:int title:string content:text
Looking at the resulting .rb file, sure enough, I saw everything I'd entered:
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
But after running rake db:migrate
and inspecting my database, I see that no user_id
column was created. What happened, here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它应该是 t.integer,而不是 t.int。请参阅文档了解更多详细信息:
Because it should be
t.integer
, nott.int
. See the docs for more details:您还可以使用:
它将创建一个名为 user_id 的整数字段。我个人更喜欢这种方法,因为它引用外键。
You can also use:
and it will create an integer field called user_id. I personally prefer this method because it's referencing a foreign key.