Thursday, May 14, 2009

Ruby on Rails MySql Connection

After creating a new ROR application by typing

>rails applicationName

command from the console, Rails creates all the required files for the newly created application.

Rails creates many folders and database related files are placed under /config folder.

It is required to add some connection info into the database.yml file which is also located under /config folder of your new Rails project.

Rails keeps database-login related data out of the application code and places that login information into database.yml file.

database.yml file contains information about database connections. That file has 3 sections for development-test-production databases.

development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: store_development
  pool: 5
  username: user
  password: userpass
  socket: /var/run/mysqld/mysqld.sock
test:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: store_test
  pool: 5
  username: user
  password: userpass
  socket: /var/run/mysqld/mysqld.sock
production:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: store_production
  pool: 5
  username: user
  password: userpass
  socket: /var/run/mysqld/mysqld.sock

adapter: section tells Rails what kind of database you are using.
database: name of the database that you want to connect to.
username&password: let's your application to login to the database.

You need to have that specified database created previously in your DBMS for connection.

For this example store_development database needs to be created previously in your mysql rdbms.

In order to create your database tables which are corresponding to models created use Rake.Rake helps to apply the migration to your database. You tell the rake to do some task and that task gets done.

>rake db:migrate

Rake looks for all the migrations not applied to the database and applies them. When it is required to add a new column to a database table, you can also use migration.

This helps you to remember what each migration does when you come back to your application at a later time.

You can create a migration explicitly by typing the command:

>ruby script/generate migration add_address

To be able to run migrations on Ubuntu 9.04 OS, also install required libmysql-ruby module.

No comments:

Post a Comment