Archive for May, 2010

Getting started with PostgreSQL when developing Rails applications

Friday, May 7th, 2010

If you’re familiar with MySQL and trying out PostgreSQL for the first time while doing some Ruby on Rails development, things can initially seem quite unfamiliar. A great first article to look at is available on the OLM on Rails site at Switching Rails to PostgreSQL. Also at this early stage in your PG career you’ll need to know how to change things like user passwords so check the Examples section of the PostgreSQL Alter User docs.

Ok, after that you should know how to create a database in PostgreSQL, hook up to a Rails app and run migrations. Once that’s done, you’ll need to be able to do the same things that you were able to do in MySQL in the psql shell. Here’s the first commands you need…

  • typing ‘help’ displays help at any time
  • \? displays help with psql commands
  • \l lists databases
  • \c some_database connects to a database
  • \c with no argument tells you what database you’re currently connected to
  • \ds lists schemas within the currently selected database. A schema is simply a namespacing of tables within a given database
  • \dt lists tables in the currently selected database
  • \du lists all postgres database user accounts (more detail here)

Here’s  a list of good of stuff…

Doing Raw MongoDB Queries when using MongoMapper with Rails

Tuesday, May 4th, 2010

Even though, you’re using MongoMapper with Ruby and Rails, you may sometimes want to do queries using the Mongo database itself. Here’s how I do it (note: there may be a better way, please post a comment).

# Getting at the mongodb instance
MongoMapper.database

# Listing its collections
MongoMapper.database.collections

# Get at any collection while within any model (note: returns a Mongo::Cursor)
coll = MongoMapper.database['questions'].find({})

# Convert that collection to an array (useful!)
coll.to_a

# Display a collection (note: ‘each’ does an implicit ‘to_a()’)
MongoMapper.database['questions'].find({}).each {|x| puts x.inspect}

# In the Question model you can use this shortcut
# collection to get at the questions collection
collection.find({}).to_a