Reputation: 305
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.
Upvotes: 3
Views: 3813
Reputation: 795
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.
Upvotes: 7
Reputation: 9
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
Upvotes: 0