英文:
"rails db:migrate" error : relation "users" does not exist?
问题
我是新手使用Rails,以下是我的问题。
我创建了一个非常简单的Rails程序,在db > migrate > 2023.._add_columns_to_user.rb文件中,我将以下代码添加到该文件中
class AddColumnsToUser < ActiveRecord::Migration[7.0]
def change
add_column :users, :full_name, :string
add_column :users, :from, :string
add_column :users, :about, :text
add_column :users, :language, :string
add_column :users, :status, :boolean
add_column :users, :status, :boolean, default: false
end
end
然后我运行了这段代码
rails db:migrate
但是它给了我这个错误
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "users" does not exist
也许我必须先创建数据库吗?
你能否就这个问题给我一些建议?
如果需要参考,以下是我所有的代码。
https://github.com/nguyencuc2586/Addcustomfieldsoutusermodel
提前感谢你。
英文:
I am newbie with rails and here is my problem.
I created a very simple rails program and in the db > migrate > 2023.._add_columns_to_user.rb file, I added this code to this file
class AddColumnsToUser < ActiveRecord::Migration[7.0]
def change
add_column :users, :full_name, :string
add_column :users, :from, :string
add_column :users, :about, :text
add_column :users, :language, :string
add_column :users, :status, :boolean
add_column :users, :status, :boolean, default: false
end
end
Then I ran this code
rails db:migrate
But it gave me this error
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "users" does not exist
May be I must create the database first?
Could you please give me some advices for this problem?
Here is all of my code, if you need for reference.
https://github.com/nguyencuc2586/Addcustomfieldsoutusermodel
Thank you in advance.
答案1
得分: 1
你不能修改尚未创建的表。你的迁移应该包含在一个表定义中:
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :full_name # 等同于 add_column :users, :full_name, :string
t.string :from
t.text :about
t.boolean :status, default: false # 为什么这是一个布尔值?
t.timestamps
end
end
end
这会生成CREATE TABLE users (...)
,而你的迁移会生成ALTER TABLE users (...)
。
英文:
You can't alter a table that hasn't yet been created. Your migration should be wrapped in a table defintion:
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :full_name # shorthand for add_column :users, :full_name, :string
t.string :from
t.text :about
t.boolean :status, default: false # why on earth is this a boolean?
t.timestamps
end
end
end
This results in CREATE TABLE users (...)
while your migration would result in ALTER TABLE users (...)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论