2013-06-27 85 views
2

添加新列這是我的用戶model.rbRails的DB不遷移

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 

但DB模式仍然

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中

而且控制檯:密碼不能在IE瀏覽器中的一個新的用戶對象添加新的數據庫條目..請建議。 P.S:我是新手,所以這可能是一個愚蠢的問題。我正在使用rails版本:3.2.13和ruby版本:1.9.3

回答

4

好的,這是關於大家都在討論的rails的「神奇」事情之一。當您進行遷移以將列添加到表時,有一個命名約定。試試這個:

rails g migration add_password_to_users password:string 

其實幾乎所有的命名約定都很重要。

+2

你還應該檢查和編輯生成器生成的任何遷移文件,然後再執行它們。 – tadman

+0

嘿,非常感謝。「神奇」是。你也可以請告訴最好的地方來學習一些其他的魔法大會。 – user2526795

+1

user2526795你會想要按照@tadman上面提到的建議。並研究Bachan Smruty發佈的代碼。在rails中做大部分事情有多種方式。 –

0

您可以按照該添加獨立遷移以下

rails generate migration AddPasswordToUsers password:string 

爲多個獨立的遷移,你可以按照鏈接。 http://guides.rubyonrails.org/migrations.html#creating-a-standalone-migration

或者你可以做另一件事。 月1日創建遷移

rails g migration AddColumnToUser 

這將創建一個數據庫遷移文件/遷移。您需要更改該文件內容。

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

+1

嗨..感謝...非常有幫助.. – user2526795