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
- Create a new project using postgresql.
rails new projectName -d postgresql
- Create the empty DB.
rake db:create
rake -T
- List all rake commands
- 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
- 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
- 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
- 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
- Add seed data to DB
rake db:seed
- Run
rails console
andModelname.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
- Generate RESTful routes. Add to config/routes.rb
resources :pluralised_tablename
- 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.