文档章节

Rake DB Commands

Kolosek
 Kolosek
发布于 2018/03/26 14:24
字数 903
阅读 4
收藏 0

Rake is a utility built into Ruby and Rails, which provides an efficient way for managing database changes. You can easily migrate database changes to servers by only using a command line!

You might be asking yourself during your application development:

  • What happens when using rake database commands?
  • When should I use them?

Let’s take a look at how we can use these commands to change our database while developing an application!

Creating

$ rake db:create
When you create your Rails application for the first time, it will not have a database yet. In order for it to start, you will need to make sure the database is up and running.

Just like it's recommended to use different gems for each environment, you should also create three databases, each for developmenttesting, and production environment. You can configure them in your config/database.yml file.

default: &default
  adapter: postgresql
  encoding: unicode
  username: username
  password: password
  host: localhost
  port: 5432

development:
  <<: *default
  database: story_dev

test:
  <<: *default
  database: story_test

production:
  <<: *default
  database: story

Migrating

rake db:migrate
Migrations setup the tables in the database. When you run the migration command, it will look in db/migrate/ for any ruby files and execute them starting with the oldest. There is a timestamp at the beginning of each migration filename.

Every time you migrate a database or make any change to it such as adding a row or a column, adding a table or changing the data type, you have to run this command for the changes to reflect in your database. List of Database Rake Tasks in a Rails Application

Migrations are created when you run commands like rails generate scaffoldrails generate model, or rails generate migration.

Here is an example how you can use rake db:migrate when uploading images. Be sure to not have data creation in the migration files!

Initializing

rake db:schema:load
Unlike rake db:migrate that runs migrations that have not run yet, rake db:schema:load loads the schema that is already generated in db/schema.rb into the database.

Always use this command when:

  • You run the application for the first time.
  • When you drop the database and you need to create it again.

Beware! If you run rake db:schema:load on a production server, you'll end up deleting all your production data.

Seeding

rake db:seed
We always have default data that we want to have in our application for testing purposes. The seed command exists to automate this process.

Example: Create an admin user and store its data in the db/seed.rb file. When you run rake db:seed it will load all the admin data into your application.

Admin.create!(email: 'admin@kolosek.com', 
              password: 'password', 
              password_confirmation: 'password')

Rails seeding is generally for development and/or staging environments, there are only a few uses in production. You don't want your production application to seed dummy users!

Rolling Back

rake db:rollback
Did you create a migration without wanting it or you simply changed your mind about it? Fear not!When you run this command, it will look at the last migration created and undo it!

Example: Let’s start off by creating a new migration with :role as an integer and run the migration. Then we decided to make it a string instead. So, we will edit the newly created migration and run it again, but nothing happens and your tests and factories will fail.

class CreateRoles < ActiveRecord::Migration
  def change
    create_table :roles do |t|
      t.integer :role # we will change this to t.string :role
      t.references :user
      t.timestamps
    end
  end
end

Why isn’t this working?
Only the last created migration is run with rake db:migrate command. This means that no changes will be made by editing an already existing migration. To make this work, you will need to run rake db:rollback instead. This will tell Rails to do two things:

  1. Undo the last changes you just made to the database.
  2. Update the migration timestamp.

Dropping

rake db:drop
Sometimes we want to delete all of the data and tables and start from fresh. That's what rake db:drop is for. If you want to keep the data you have, be sure to back it up before running this command.

Dropping the database will also remove any schema conflicts or bad data. Once the database is dropped, you'll want to start the process over again by re-creating the database, running migrations, and seeding the data. Be sure that your RSpec tests are passing after remaking your database!

Make sure you don't have connections to the database or it won't drop.

Resetting

rake db:reset
You might sometimes need to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following:

  1. Drop the database: rake db:drop
  2. Load the schema: rake db:schema:load
  3. Seed the data: rake db:seed

Why db:schema:load and not db:migrate?
rake db:schema:load is much faster than rake db:migrate, because it loads the schema that we’ve already generated from db/schema.rb instead of going through all the migrations again.

Hope this helped you to understand the main difference between rake database commands!

Originally published on Kolosek Blog.

© 著作权归作者所有

Kolosek
粉丝 0
博文 29
码字总数 20461
作品 0
塞尔维亚
CEO
私信 提问
执行rake db:migrate时的两个错误

rails的确是来的方便,一个rails generate scaffold命令下来就可以生成view、controller和model的所有文件,然后再执行rake db:migrate就可以生成相应的数据库表结构。而就是这个简单的rake ...

kjmeng
2011/07/05
0
0
remine windows 2003 安装

提醒,版本一定不能用太高的,尤其是redmine,我在这个问题上折腾很久。以下给出的版本号都是安装成功的。 remine不需要apache,php,等环境。 1. 给DOS添加ruby运行环境(下载并安装 rubyin...

v289
2016/07/31
0
0
gitlab 备份报错

各位大咖,我在执行gitlab备份的时候提示报错,信息如下,请问这个问题要怎么解决,先说声多谢!! [root@git gitlab]# gitlab-rake gitlab:backup:create --trace ** Invoke gitlab:backup:...

xiaosayi
2018/05/23
441
0
Ruby on Rails 之旅(二)—— 牛刀小试

上一篇博文中介绍了如何配置windows下的ROR开发环境。 1)创建工程: File->New->Rails Project 输入Project名,DB选择PostgreSQL,finish之后工程就直接创建完毕了。 2)修改DB访问配置: ...

jing31
2010/08/09
3.1K
0
Mac 下 Rails 使用 MySQL 驱动的问题:Library not loaded: libmysqlclient.18.dylib

给 Rails 配置了 MySQL: 执行 bin/rake db:migrate 时报错: LoadError: dlopen(/Library/Ruby/Gems/2.0.0/gems/mysql2-0.3.16/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmys......

红薯
2014/08/19
1K
3

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周六乱弹 —— 如果是个帅小伙你愿意和他出去吗

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 小小编辑推荐:《Ghost 》游戏《死亡搁浅》原声 《Ghost 》游戏(《死亡搁浅》原声) - Au/Ra / Alan Walker 手机党少年们想听歌,请使劲儿戳...

小小编辑
28分钟前
28
3
java通过ServerSocket与Socket实现通信

首先说一下ServerSocket与Socket. 1.ServerSocket ServerSocket是用来监听客户端Socket连接的类,如果没有连接会一直处于等待状态. ServetSocket有三个构造方法: (1) ServerSocket(int port);...

Blueeeeeee
今天
6
0
用 Sphinx 搭建博客时,如何自定义插件?

之前有不少同学看过我的个人博客(http://python-online.cn),也根据我写的教程完成了自己个人站点的搭建。 点此:使用 Python 30分钟 教你快速搭建一个博客 为防有的同学不清楚 Sphinx ,这...

王炳明
昨天
5
0
黑客之道-40本书籍助你快速入门黑客技术免费下载

场景 黑客是一个中文词语,皆源自英文hacker,随着灰鸽子的出现,灰鸽子成为了很多假借黑客名义控制他人电脑的黑客技术,于是出现了“骇客”与"黑客"分家。2012年电影频道节目中心出品的电影...

badaoliumang
昨天
16
0
很遗憾,没有一篇文章能讲清楚线程的生命周期!

(手机横屏看源码更方便) 注:java源码分析部分如无特殊说明均基于 java8 版本。 简介 大家都知道线程是有生命周期,但是彤哥可以认真负责地告诉你网上几乎没有一篇文章讲得是完全正确的。 ...

彤哥读源码
昨天
19
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部