Rails 101 (once and for all)#

This is the sequence to develop

rails new project#

Create new app#

> rails new app-name -T --api --database sqlite3/postgresql

Use `bundle info [gemname]` to see where a bundled gem is installed.
    run  bundle binstubs bundler
    rails  webpacker:install
gem 'active_model_serializers'  # serialise & assoc between models
gem 'faker'                     # seed DB with dummy data

Setup Database interface & models#

setup database -> configure the environment#

database.yml configure it up rails db:create -> will create the empty db (confirm collateral)

rails g scaffold User name:String

rails g scaffold Post user:references title:text body:text

rails g scaffold Comment post:references user:references body:text

manual additions to db/model (for each above as necessary), establish further relationships#

The models will have:

> post belongs_to :user
> add  has_many :posts

rails db:migrate # will add additional tables (models) into the database

rails db:seed

gem '..serializers'#

the scaffold has created app/serializers/*.rb for each of the models


Having completed a rails db:migrate of the original tables, when you wish to extend / change the models, you create a new migration

> rails g migration add_admin_to_user

which will create a new entry in db/migrate/add_admin_to_user.rb


Rails.application.routers.draw do
  namespace :api, :defaults => {:format => :json} do
    get  "/contacts",       to: "contacts#index"
    post "/contacts"
    get  "/contacts/:id"
    put  "/contacts/:id"
    delete  "/contacts/:id"

Support versioning#

Rails.application.routers.draw do
  namespace :api, :defaults => {:format => :json} do
    namespace :v1 do
      get  "/contacts",       to: "contacts#index"

"namespace :api" just adds "/api/URI" ("add /api/" in front of URI)

rails routes -> will show what's available as path (use Postman at this stage to tackle data)

In chrome

localhost:3000/rails/info/routes -> same content as on command line

Rails status 200
Rails status 200 show Get of a single item.
422 Unprocessable
201 create
verbose errors from db

Query Strings#

/contacts?relationship=friend (filtering)
/contacts?order=created_at:desc (sort order) /contacts?25?include=notes (Side-load associated resources)

Sort this later#


# config/environments/production.rb
MyApp::Application.configure do
  config.force_ssl = true


Set 'etag' & 'last_modified' in the response header to assist with cacheing If both haven't been modified since last call, 304 Not Modified will be sent back


rails db:migrate VERSION=0 # roll back the DB rails db:reset # drops all tables, calls seeds.rb


def set_contact_name
  raise params.inspect


def preview
  render :layout => false


rails -T # dump all tasks


rails g migration add_user_table
rails g model User

does this even exist?#

resources projects do
  collection do
    get 'archived', to: 'controller/action'

  member do
    post 'archive', to: 'controller/archive'