Monday, July 21, 2008

Accessing MySQL from Ruby

Here is a simple example to access mysql tables from Ruby using active record class.

  • Install Ruby Gem "active_record"
C:\Vijay\ruby>gem install activerecord
Updating metadata for 182 gems from http://gems.rubyforge.org/
..........................................................................................
...............................................
complete
Bulk updating Gem source index for: http://gems.rubyforge.org/
Successfully installed activerecord-2.1.0
1 gem installed
Installing ri documentation for activerecord-2.1.0...
Installing RDoc documentation for activerecord-2.1.0...
  • Create a database called Students (or anything you like) and create a table inside it called Products (following rails naming convention, plurals for tables)
mysql> create database students;
Query OK, 1 row affected (0.05 sec)

mysql> create table products(id int not null auto_increment,
-> name varchar(255) not null,
-> description text,
-> price float(5,2) not null,
-> primary key(id));
Query OK, 0 rows affected (0.11 sec)

mysql> desc products;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| description | text | YES | | NULL | |
| price | float(5,2) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0.14 sec)





Getting started in Ruby on Rails

Coming soon