Skip to content

Instantly share code, notes, and snippets.

@timiscoding
Last active December 31, 2015 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timiscoding/44894d4b2464db5fb797 to your computer and use it in GitHub Desktop.
Save timiscoding/44894d4b2464db5fb797 to your computer and use it in GitHub Desktop.
Rails app with seeded postgresql db

Creating a rails app with a prepopulated postgres db

Prerequisite: make sure Postgres is started! You should see the elephant icon in the menu bar

Plural for table names and controller names, singular for models

  1. Create a new project using postgresql.
rails new projectName -d postgresql
  1. Create the empty DB.
rake db:create

rake -T - List all rake commands

  1. Generate db/migrate/timestamp_create_tableName.rb stub file.
rails generate migration create_pluralised_tablename # can also use CreatePluralisedTablename

Fill in column data and type so rails can create the schema. This is like writing .sql scripts.

create_table :pluralised_tablename do |t| # must use camel case
    t.text :name # no commas after each field!
    ...
    t.timestamps
end
  1. Create the table in postgres
rake db:migrate

Confirm the table data in db/schema.rb. If you make a mistake, undo the last migrate with rake db:rollback

  1. Hook up active record. Create app/models/singularisedModelname.rb and add
class SingularisedModelname < ActiveRecord::Base # first letter of class name must be capitalised
end

Run annotate to update model with schema comments

  1. Pre-populate DB by adding data to db/seeds.rb
Modelname.destroy_all # clobber everything in DB first
Modelname.create(:colName => data, ...) # active record method to create new row data
  1. Add seed data to DB
rake db:seed
  1. Run rails console and Modelname.all to check data is all there. If you've mispelt/forgotten a field, update the migrate file (step 3) then do
rake db:drop
rake db:create
rake db:migrate
rake db:seed
  1. Generate RESTful routes. Add to config/routes.rb
resources :pluralised_tablename
  1. Generate controller actions and views.
rails generate controller Pluralised_controllername action1 action2 # eg. Artists index new edit show

Remove redundant routes from config/routes.rb

To add a foreign key to your table:

rails generate migration add_singularised_tablename_id_to_pluralised_tablename # eg. add_artist_id_to_works

This should add artist_id:integer to the migrate file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment