Thursday, September 9, 2010

Connect to database using ruby and ActiveRecord


To get connected to your database from your ruby file just include the "ActiveRecord" inside your ruby file.

require 'rubygems'
require 'activerecord'

#establish the connection.
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:database => "database",
:username => "username",
:password => "password",
:host => "localhost"
)

#create a class inherit with you activerecord base class.
class User < ActiveRecord::Base
end

user = User.find(:first)
puts user
Or

class SomeThing < ActiveRecord::Base
set_table_name :users
end

user = SomeThing.find(:first)
puts user

*************************************
another option would be using PGConn.

gem install pg -v 0.11.0

then run this on your script

conn = PGconn.connect("localhost",port#,"","","database_name","username","password")
var_1 = conn.exec("select * from table where column='value'")
var_2 = var_1.first['column2]
puts var_2

5 comments:

  1. this is a very good post.. i like ilike!

    ReplyDelete
  2. nice post. true true true.

    also you can try this:

    http://blog.aizatto.com/2007/05/21/activerecord-without-rails/

    ReplyDelete
  3. haha, nice post! :) pwede ka bang mkilala?

    ReplyDelete
  4. ahahaha adik ka Xy!
    turon ka ba? =))

    ReplyDelete