Wednesday, September 23, 2009

JRuby on Rails: using JDBC driver

In JRuby world the bridge between Rails activerecord and JDBC driver is activerecord-jdbc-adapter. activerecord-jdbc-adapter allows you to use virtually any JDBC-compliant database with your JRuby on Rails application. You can verify the supported JDBC-compliant database by going to JRUBY_HOME\lib\ruby\gems\1.8\gems\activerecord-jdbc-adapter-0.8\lib\active_record\connection_adapters. For every supported database you will have databasename_adapter.rb file. Please see my blog 'Oracle with JRuby using activerecord-jdbc-adapter' to install JRuby, Rails and activerecord-jdbc-adapter and test your installation is correct.

Now its time to configure the database.yml file. Since version 2.0 Rails automatically look for and load an adapter gem based on the name of the adapter you specify in database.yml. Example:

development:
adapter: jdbc
...

With this database configuration, Rails will attempt to load the activerecord-jdbc-adapter gem. Here is an example for oracle database:

development:
adapter: oracle
driver: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521:XE
username: username
password: password

If you want to work with the connection itself then require the active_record/connection_adapters/jdbc_adapter library and call the method ActiveRecord::Base.jdbc_connection in order to obtain a connection to the database:

require 'rubygems'
require 'active_record'
require 'active_record/connection_adapters/oracle_adapter'

ActiveRecord::Base.jdbc_connection

In upcoming blog I am going to write on using JNDI in your JRuby on Rails application and deploying in JBoss.

No comments: