新手问题 Rails 里面数据库变更操作

bluesky0318 · October 16, 2014 · Last by flowerwrong replied at October 16, 2014 · 3480 hits

做为新手,经常碰到的问题就是数据库建立了,比如 rake db:create 然后也 rake db:migrate 了,然后写着写着发现数据库里面字段不够用了,这个时候要 add column,或者多了要 Remove column,这个时候怎么操作啊?我是 Rails 4. 还有就是常常建立了一个 model 后,migrate 了,删除 model 后,怎么删除对应的 db 呢?有的时候用 rollback 还行,但是如果都操作都好多步了,要回去都不晓得怎么搞了,有好几次都用 drop 把所有数据库都干掉了,所以想请问就是这种情况如何弄呢?请高手指教。

也查过好些资料,写的都蛮笼统的,有没有详细点的操作步骤,谢谢了

我想应该对所有支持的数据库操作都一样的吧,不会要去区分 mysql 还是 pg,or sqlite3 吧

http://guides.rubyonrails.org/migrations.html

rails generate migration AddDetailsToProducts
rake db:migrate VERSION=20080906120000
rake db:drop
rake db:create
rake db:migrate
rake db:seed
rake db:reset # ==前面四条
rake db:setup # rake db:create & rake db:migrate & rake db:seed

看看rake -T

删除的时候也是建 Migration 执行删除动作。 请阅读: http://guides.ruby-china.org/active_record_migrations.html

@flowerwrong @huacnlee 谢谢二位,这个我也看过,但是操作起来怎么都不起作用,而且越发搞得数据库里面很乱

多试试,手动编辑 migration 文件也是可以的,添加字段rails generate migration AddDetailsToProducts rake -T | grep db:

rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:c...
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:dro...
rake db:fixtures:load                   # Load fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clear a db/schema_cache.dump file
rake db:schema:cache:dump               # Create a db/schema_cache.dump file
rake db:schema:dump                     # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load                     # Load a schema.rb file into the database
rake db:seed                            # Load the seed data from db/seeds.rb
rake db:setup                           # Create the database, load the schema, and initialize with the seed data (use db:reset to also dro...
rake db:structure:dump                  # Dump the database structure to db/structure.sql
rake db:version                         # Retrieves the current schema version number
You need to Sign in before reply, if you don't have an account, please Sign up first.