Ruby on Rails 使用mysql数据库 use local and remote mysql in development production environments in Ruby o

将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

将当前内容替换为以下内容。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删掉。


4.在production环境下测试配置是否成功。如果遇到问题可以参考我的另一篇博客。 配置远程连接mysql数据库 Connect to remote mysql database
$ 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
修改网页上的数据后,查看对应的数据库中数据是否改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值