更正 Ruby on Rails Database.yml 文件的 MySQL 配置

我有这样的配置:

development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: mysql://127.0.0.1:3306

我得到了这个错误:

Unknown MySQL server host 'mysql://127.0.0.1:3306' (1)

有没有什么明显的地方我做错了?

126863 次浏览

You should separate the host from the port number. You could have something, like:

development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306

If you have multiple databases for testing and development this might help

development:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

$ cat config/database.yml
 
$ echo $DATABASE_URL
mysql://root:my_password@127.0.0.1:3306/my_db_name

for Heroku: heroku config:set DATABASE_URL='mysql://root:my_password@host.com/my_db_name'

You also can do like this:

default: &default
adapter: mysql2
encoding: utf8
username: root
password:
host: 127.0.0.1
port: 3306


development:
<<: *default
database: development_db_name


test:
<<: *default
database: test_db_name


production:
<<: *default
database: production_db_name

Use 'utf8mb4' as encoding to cover all unicode (including emojis)

default: &default
adapter: mysql2
encoding: utf8mb4
collation: utf8mb4_bin
username: <%= ENV.fetch("MYSQL_USERNAME") %>
password: <%= ENV.fetch("MYSQL_PASSWORD") %>
host:     <%= ENV.fetch("MYSQL_HOST") %>

(Reference1) (Reference2)