嘿伙计们,当我第一次开始一个rails项目时,模型用户就被设计和创建了。在所有迁移部分之后,它成功地在postgres创建了表“users”。 好吧,然后在项目期间做了一些更改后,我意识到在表中缺少一个属性/新列。
所以我做的是从postgres中删除表用户并在我的第一个迁移ruby类中添加一个新列:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :password
t.string :email
t.string :authorization_token //this is the new attribute that I insert
t.datetime :created_at
t.datetime :updated_at
t.timestamps
end
end
def self.down
drop_table :users
end
end
因此,当我再次运行db:migrate hopping时,将使用新属性:authorization_token创建新用户表,它不起作用,但没有错误。
(我知道我不应该删除表格,还有另一种聪明的方法可以做到这一点)
答案 0 :(得分:3)
使用Rails的提示 - 不要使用SQL手动修改表。当你看到这个问题时,你应该编写一个像@nruth所示的新迁移。运行rake:migrate命令对你来说没问题。
在这种情况下,由于您已经删除了“用户”表,因此您现在遇到的问题是您的数据库架构与Rails认为的不同步。要解决此问题,您可以通过手动创建“用户”表,运行向下迁移,然后向上迁移,使数据库模式与Rails认为的大致匹配。或者你可以通过“用户”表不再存在的事实来快速获得Rails。 Rails在schema_info表(Rails&lt; 2.1)或schema_migrations表(Rails&gt; = 2.1)中存储迁移信息。如果删除该表,则Rails会认为架构不存在,并尝试运行所有向上迁移并再次为您重新创建“用户”表。
最后,随着时间的推移,您可能会累积一些迁移,这些迁移会单独添加您忘记包含的一两列。如果您还没有发货或尚未投入生产,那么您可以编写一个基准列表的迁移。它看起来像这样:
class CreateBaselineUsers < ActiveRecord::Migration
def self.up
create_table :users, :force => true do |t|
t.string :name
...
这将强制删除表并使用您想要的所有属性重新创建它。
答案 1 :(得分:2)
迁移运行一次&amp;存储在数据库中已经使用过(查看schema_migrations表)。您可以尝试使用rake db:migrate:reset来重新运行初始迁移,但最好只添加新的迁移(当数据库中包含数据时,您不希望将数据库吹掉),如下所示:
脚本/生成迁移add_authorization_token_to_users authorization_token:string
将生成类似于以下内容的内容:
class AddAuthorizationTokenToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.string :authorization_token //this is the new attribute that I insert
end
end
def self.down
remove_column :users, :authorization_token
end
end
要查看add / remove column,change_table等是如何工作的,请查看http://api.rubyonrails.org或http://guides.rubyonrails.org/migrations.html上的ActiveRecord :: ConnectionAdapters :: SchemaStatements