3

I am new to ruby. What is the best approach to make a simple postgresql DB via a ruby script? Can I use active record for this (not sure if it can be used via a ruby script)? or there are better alternatives?

I appreciate if you could help me with a ruby code snippet, or redirect me through a link.

Thanks.

2
  • i don't understand what you mean, are you want to create new rails app and database app will use is postgres? Commented Nov 10, 2012 at 6:29
  • @Kien Thanh: No, I just wanna make a simple ruby script to be connected to a postgresql database. Commented Nov 10, 2012 at 6:39

2 Answers 2

7

I agree with AlexFranco that you can easily achieve that with the pg gem. However, when you read how to use the pg gem you might wonder which database you should connect to.. after all you want don't have a database yet, if you had you wouldn't want to create one..

Turns out there is a master-db called postgres. So here's a minimal working example:

require 'pg'

conn = PG.connect(dbname: 'postgres')
conn.exec("CREATE DATABASE foo")

See the postgresql documentation on options for the create database statement. More info on how to use the pg gem can be found in the docs.

Sign up to request clarification or add additional context in comments.

Comments

0

I think, you can try with the pg gem,

#!/usr/bin/env ruby

require 'pg'

# Output a table of current connections to the DB
conn = PG.connect( dbname: 'sales' )
conn.exec( "SELECT * FROM pg_stat_activity" ) do |result|
  puts "     PID | User             | Query"
  result.each do |row|
    puts " %7d | %-16s | %s " %
      row.values_at('procpid', 'usename', 'current_query')
  end
end

Here is the link where you can find information,and this example https://bitbucket.org/ged/ruby-pg/wiki/Home

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.