将Ruby on Rails 使用的数据库由默认的SQLite改成Mysql,并且配置development为本地mysql,production为远程mysql。
1.修改config/database.yml
$ cd config
$ cp -p database.yml database.yml.old
$ vim database.yml
2.配置Gemfile
添加 gem 'mysql2',完整配置如下:
3.在development环境下测试配置是否成功。
$ bundle install --without production
$ bundle update
$ bundle install
$ rake db:create
$ rake db:migrate
执行后进入mysql查看development中配置的数据库demo_app_dev_db是否生成,以及里面的table是否生成。
$ rails s
修改网页上的数据后,查看对应的数据库中数据是否改变。
$ bundle install --without development test
$ bundle update
$ bundle install
$ rake db:create RAILS_ENV=production
$ rake db:migrate RAILS_ENV=production
执行后进入mysql查看production中配置的数据库demo_app_prod_db是否生成,以及里面的table是否生成。
$ rails s -eproduction
修改网页上的数据后,查看对应的数据库中数据是否改变。
1.修改config/database.yml
$ cd config
$ cp -p database.yml database.yml.old
$ vim database.yml
将当前内容替换为以下内容。dabase,username,password,host依自己的情况而定。如果username没有password,则留空白。database指定的数据库名会在bundle install的时候被安装在相应的host上。
#use localhost mysql
development:
adapter: mysql2
encoding: utf8
database: demo_app_dev_db
pool: 5
username: root
password:
host: localhost
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: mysql2
encoding: utf8
database: demo_app_test_db
pool: 5
username: root
password:
host: localhost
#use remote host mysql
production:
adapter: mysql2
encoding: utf8
database: demo_app_prod_db
pool: 5
username: yangpeng
password: ***
host: ***.***.***.***
2.配置Gemfile
添加 gem 'mysql2',完整配置如下:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.5'
gem 'mysql2'
group :development do
end
gem 'sass-rails', '4.0.5'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.1'
gem 'jquery-rails', '3.0.4'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :test do
gem 'sdoc', '0.3.20', require: false
end
group :production do
#gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
3.在development环境下测试配置是否成功。
$ bundle install --without production
$ bundle update
$ bundle install
$ rake db:create
$ rake db:migrate
执行后进入mysql查看development中配置的数据库demo_app_dev_db是否生成,以及里面的table是否生成。
$ rails s
修改网页上的数据后,查看对应的数据库中数据是否改变。
注意,执行bundle install --without production后,会在.bundle/config里自动生成配置文件,这样第二次执行bundle install时候不指定--without production也和
bundle install --without production效果一样,所以在执行步骤4前,应该先修改该config文件,将里面的BUNDLE_WITHOUT: production删掉。
$ bundle install --without development test
$ bundle update
$ bundle install
$ rake db:create RAILS_ENV=production
$ rake db:migrate RAILS_ENV=production
执行后进入mysql查看production中配置的数据库demo_app_prod_db是否生成,以及里面的table是否生成。
$ rails s -eproduction
修改网页上的数据后,查看对应的数据库中数据是否改变。