问题
I am really new in Ruby on Rails. I have read this tutorial and it sounds really easy.
But how can I connect to my database (MySQL) or what does Rails use? In php I'd use...
mysql_connect("...","...","...");
mysql_select_db("...");
I have searched google and cannot find any useful tips.
回答1:
You don't have to do those things manually, check this: http://guides.rubyonrails.org/configuring.html#configuring-a-database
回答2:
Have a look into the configuration file config/database.yml
You need to setup your configuration there. Here is an example for the production environment:
production:
adapter: mysql2
encoding: utf8
database: example
pool: 10
username: example
password: secure
socket: /var/run/mysqld/mysqld.sock
reconnect: true
In addition to that you have to add gem 'mysql2' in your Gemfile and run bundle install.
回答3:
Contents of my config/database.yml file:
# Ensure the MySQL gem is defined in your Gemfile
# gem 'mysql2'
#
# Install MySql gem if not already there.
# Below command installs some pre-requisites for the installation:
# sudo apt-get install libmysqlclient-dev mysql-client
# After above, this to finish gem installation:
# gem install mysql2
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: YOUR_DATABASE_HERE
pool: 5
username: root
password: root
As the comments above the configurations say, you might need to install the mysql2 gem first via the terminal. After installation is finished, do a bundle install and rake db:migrate and can then access the database via phpmyadmin too.
I had just stumbled upon this question an hour ago, more than 2 years later since the question was asked. Although I understand this is very late and for sure OP must have solved this, for the sake of other beginner users like me who might be coming here for a solution, I thought of writing my solution here. Hope it helps.
来源:https://stackoverflow.com/questions/15613646/how-can-i-connect-to-mysql-in-ruby-on-rails