Posts Tagged ‘database’

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…

Generate Rails Migrations from your PostgreSQL or MySQL database

Thursday, November 26th, 2009

1) Create a new empty Rails project called schemer

2) In your config/database.yml file, point at the database you wish to dump to a migrations file

3) Run the command ‘rake db:schema:dump’. This should create a db/schema.rb file. Amazingly this effectively is your migrations file!

4) To tidy up create a file called file db/migrate/20091125205635_create_initial_schema.rb

5) Then copy the create_table statements from the schema.rb file into the new file 20091125205635_create_initial_schema.rb. Here’s a template

class CreateInitialSchema < ActiveRecord::Migration

  def self.up
    # Put all create_table statements from schema.rb file here
    # Note: You don't need the 'ActiveRecord::Schema.define(:version' line or it's enclosing end statement
    # ...
    # ...
  end

  def self.down
    # Don't really need this
  end

end

6) Once you’ve all this done you can just run ‘rake db:migrate’ and you should have a new sqlite db up and running under db/development.sqlite3

Thanks to Justin Ball on this Nobody Listens Anyway blog at Dump an Existing Database Schema Into a Ruby On Rails Migration Ready Format for the basis of this tip. Sometimes somebody does…