Manual active record db connection


Guy’s quick tour, how to connect standalone ruby file to mysql datababase. You can follow steps to understand procedure OR clone my working sample example active recored connection

1. Install relevant gems.
sudo gem install activerecord
sudo gem install yaml_db
sudo gem install logger

2. Create a ruby file and add below code.

require ‘rubygems’
require ‘active_record’

ActiveRecord::Base.establish_connection(
:adapter => ‘mysql’,
:database => ‘test’,
:username => ‘root’,
:password => ”,
:host => ‘localhost’)

when we run this file from rails console it should run without any error and output.

3. Now create table LOCATIONS in test database and insert some row.

mysql> create table locations(name varchar(100), city varchar(100));
Query OK, 0 rows affected (0.60 sec)

mysql> show tables;
+—————-+
| Tables_in_test |
+—————-+
| locations |
+—————-+
1 row in set (0.28 sec)

mysql> insert into locations(name,city) values(‘Sanyam’,’Bettiah’);
Query OK, 1 row affected (0.12 sec)

mysql> insert into locations(name,city) values(‘Sanyam’,’Bettiah’);
Query OK, 1 row affected (0.21 sec)

mysql> select * from locations;
+——–+———+
| name | city |
+——–+———+
| Ankit | Asansol |
| Sanyam | Bettiah |
+——–+———+
2 rows in set (0.00 sec)

4. Add ruby class and inherit ActiveRecord::Base, So we can perform database operation.

class Location < ActiveRecord::Base
end

5. Add initialize action to access database and execute some command.

class Location < ActiveRecord::Base

def initialize
p 'Tables details'
p Location

p 'Count no of rows in table'
p Location.count
end

end

Location.new

6. Run ruby file from command line, it supposed to display

pravinmishra@ubuntu:~/workSpace/RUBY_CODE/active_record_connection/lib$ ruby main.rb
“Tables details”
Location(name: string, city: string)
“Count no of rows in table”
2

that’s it.

Addition we can separate data configuration in different file and add logger to display sql query OR errors if any. I did all this two setups in active recored connection , You can take a look. 🙂

Cheers!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s