Created
March 24, 2012 00:34
-
-
Save yokolet/2176753 to your computer and use it in GitHub Desktop.
Rails 3: How to add a new field to an existing database table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Existing schema is below: | |
ActiveRecord::Schema.define(:version => 20120130161449) do | |
create_table "movies", :force => true do |t| | |
t.string "title" | |
t.string "rating" | |
t.text "description" | |
t.datetime "release_date" | |
t.datetime "created_at" | |
t.datetime "updated_at" | |
end | |
end | |
To add new field "director" to this schema, I created Migration by: | |
rails g migration AddDirectorToMovie director:string | |
The name "AddDirectorToMovie" means much. "Add" creates "change" method in Migration, and "ToMovie" indicates the table concerned about is "movies." | |
So, I got a migration file, db/migrate/20120323210944_add_director_to_movie.rb whose contents is: | |
class AddDirectorToMovie < ActiveRecord::Migration | |
def change | |
add_column :movies, :director, :string | |
end | |
end | |
One last thing to do is: | |
rake db:migrate | |
Now, I have an updated schema.rb: | |
ActiveRecord::Schema.define(:version => 20120323210944) do | |
create_table "movies", :force => true do |t| | |
t.string "title" | |
t.string "rating" | |
t.text "description" | |
t.datetime "release_date" | |
t.datetime "created_at" | |
t.datetime "updated_at" | |
t.string "director" | |
end | |
end | |
Also, I could confirm the "director" field was added on Rails console: | |
1.9.2p290 :012 > Movie.columns.map {|c| c.name} | |
=> ["id", "title", "rating", "description", "release_date", "created_at", "updated_at", "director"] | |
Thank you! This worked for me.
It really works ...
thanks!
thanks! 👍 😄
thanks!
Thank You!
Thank you!
Wooo! Still works on Rails 5.2.3 in 2021!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you please tell me why it doesn't work if I add the
change
method directly intodb/migrate/20111119180638_create_movies.rb
?