2015-11-06 81 views
1

我用下面的代碼字段director添加到現有的movies表:添加列到現有的表

class CreateMovies < ActiveRecord::Migration 
    def up 
    create_table :movies do |t| 
     t.string :title 
     t.string :rating 
     t.text :description 
     t.datetime :release_date 

     # Add fields that let Rails automatically keep track 
     # of when movies are added or modified: 
     t.timestamps 
    end 

    add_column :movies, :director, :string 
    end 


    def down 
    drop_table :movies 
    end 
end 

我已經看到this,但difrence是我堅持使用

rake db:test:prepare command after i add my new field. 

當我運行rake db:test:prepare,然後我跑我的cucumber,它給我的erorr:

unknown attribute 'director' for Movie. (ActiveRecord::UnknownAttributeError) 

,這意味着我無法在現場director添加到table movies, 那麼,什麼是錯在這裏?

+0

檢查你已經把這個功能「導演」放在了參數中。 –

+2

[將列添加到Rails遷移中的現有表](http://stackoverflow.com/questions/4834809/adding-a-column-to-an-existing-table-in-a-rails-移民) – weezing

回答

0

db:test:prepare使用db/schema.rb重新創建數據庫。

這將解決您的問題:

bin/rake db:rollback 
bin/rake db:migrate 
0

當你做任何遷移,它被保存在架構

回滾,移民,進行更改,然後再進行遷移

例如,如果20150923000732_create_movies.rb遷移是您可以回滾的最後一次遷移:

rake db:rollback 

否則,你可以簡單地降低您的使用特定版本的遷移:

rake db:migrate:down VERSION=20150923000732 

回滾遷移,改變你的遷移文件,並再次遷移後。

2

試試下面的代碼:

rails g migration AddDirector 

然後,在相應的遷移 def change add_column :movies, :director, :string end 執行,rake db:migrate

在電影控制器,在控制器中添加 「導演」 在movie_params