Rails数据库迁移未能添加新列

3
这是我的User模型.rb。
class User < ActiveRecord::Base
    attr_accessor :password
  attr_accessible :email, :name

  validates :name,:presence=>true,:length=>{:maximum=>15}
    validates :email,:presence=>true,:length=>{:maximum=>15}
end

我想添加一个新的密码列。 我使用了以下命令:

rails g migration pass_mig password:string

那么

rake db:migrate

但在数据库架构中仍然存在

ActiveRecord::Schema.define(:version => 20130627073430) do

      create_table "users", :force => true do |t|
        t.string   "name"
        t.string   "email"
        t.datetime "created_at", :null => false
        t.datetime "updated_at", :null => false
      end
end

在Rails控制台中:不能在新的User对象中添加密码,即不能在新的数据库条目中添加密码。请建议。 附言:我是Rails的新手,所以这可能是一个愚蠢的问题。我正在使用Rails版本:3.2.13和Ruby版本:1.9.3
2个回答

6

好的,这是Rails中每个人都经常谈论的那些“神奇”事情之一。当您执行迁移以向表添加列时,有一个命名约定。请尝试以下操作:

rails g migration add_password_to_users password:string

实际上,几乎所有事物都有重要的命名约定。

2
在执行迁移文件之前,您还应该检查和编辑生成器生成的任何迁移文件。 - tadman
非常感谢你。它很“神奇”。你能告诉我学习其他“神奇约定”的最佳途径吗? - user2526795
1
你会想要遵循@tadman上面提到的建议。同时也要研究Bachan Smruty发布的代码。在Rails中,大多数事情都有多种方法来完成。 - Matthew Graves
如果你正在寻找更多关于Rails的工作方式的建议,有许多书籍可能会提供你所需要的示例。 - tadman
@tadman 好的,谢谢。看起来正是我正在寻找的东西。 - user2526795

0

您可以按照以下方式添加独立迁移

rails generate migration AddPasswordToUsers password:string

如果您需要更多的独立迁移,请访问以下链接。 http://guides.rubyonrails.org/migrations.html#creating-a-standalone-migration

或者您可以采取另一种方法。 首先创建一个迁移。

rails g migration AddColumnToUser

这将在db/migrate中创建一个迁移文件。您需要更改该文件的内容。

class AddColumnToUser < ActiveRecord::Migration
  def change
    # all the codes being generated automatically. The following you need to write.
    add_column :users, :password, :string   # this means you are adding password having string type in users table.
  end
end

完成上述步骤之一后,只需执行rake db:migrate即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接