How to create a new Rails Page

Leave a comment

Some notes to remind me of the generators and classes necessary for creating a new rails page.

Start with a new generator

> rails generate controller Sessions –no-test-framework

Add some routes

SampleApp::Application.routes.draw do
  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  root  'static_pages#home'
  match '/signup',  to: 'users#new',            via: 'get'
  match '/signin',  to: 'sessions#new',         via: 'get'
  match '/signout', to: 'sessions#destroy',     via: 'delete'


Create the initial controller

class SessionsController < ApplicationController

  def new

  def create
    render 'new'

  def destroy

Manually create a new page


<% provide(:title, "Sign in") %>
<h1>Sign in</h1>

Links that help


Rails has_many example

Leave a comment

Here are some notes on how to create a has_many relationship and the corresponding APIs for each entity.

> rails new hasMany
> rails g scaffold User name:string
> rails g scaffold Micropost content:string user_id:integer


class User < ActiveRecord::Base
   has_many :microposts, dependent: :destroy


class Micropost < ActiveRecord::Base
  belongs_to :user

Sample calls

> micropost.user
> user.microposts
> user.microposts.create(arg)
> @micropost = “Lorem ipsum”)

Links that help

How do rails environments work?

Leave a comment

Rails environments are wonderful. But they can be a bit confusing do to some inconsistency in terms of which environments are affected when you run certain rake tasks.

After some digging I think I figured it out.

db:create – affects both development and test environments
db:drop – only affected development (though this has changed)
db:migration – runs against your current environment (usually development)

hence the need for
db:test:prepare (to apply migrations against your test environment)

So in summary, you always need to specify the environment your rake tasks run against

$ rake foo RAILS_ENV=test

With the exception of db:create and db:drop above.

Links that helped:

How to setup Rails3 postgres on mac



A much better way to install Postgres locally is to use

Do this and use the following commands to create your local root user (with no password) and database instance.

psql template1 -h localhost
CREATE DATABASE <your db name>;
GRANT ALL PRIVILEGES ON DATABASE <your db name> to root;


Wanting to align with Heroku I decided to setup a local instance of postgres.
It was more complicated than I would have liked, but here are some sketchy notes that might help if you need to go through the same thing.

Install postgres

$ brew install postgresql

After trying the EnterpriseDB one click deploy I found the homebrew install most stable.

Create Rails3 app with postgres as database

$ rails new pg -d postgres

Create new postgres database user

$ cd
$ sudo su postgres
$ createuser jr
$ Shall the new role be a superuser? (y/n) y
$ exit

if you get a getcwd: cannot access parent directories: Permission denied
just type ‘cd’ or ‘cd /’ and goto a directory where permissions aren’t an issue.

Create databases

$ sudo su postgres
$ psql template1

template1=# \l
template1=# CREATE DATABASE pg_development;
template1=# CREATE DATABASE pg_test;
template1=# \q

Login to terminal

$ psql -U postgres -d pg_development


adapter: postgresql
encoding: unicode
database: pg_development
pool: 5
username: postgres
password: root

adapter: postgresql
encoding: unicode
database: pg_test
pool: 5
username: postgres
password: root

This was all setup and pre-populated. Only had to set username and password.


$ rake db:create
$ rails generate scaffold Post name:string title:string content:text
$ rake db:migrate

Should be good to go. If you run into problems let me know and I will try to keep this up to do.

kill hanging postgres processes

Sometimes I have to manually kill postgres instances when I do a redeploy.
Pattern I follow is:
> (rebuild database)
> sudo kill -9
> manually restart server using pgadmin
> restart local rails server

— it’s a pain and I will update this when I find a better way


Links that helped

How to embed HTML within a rails flash response

Leave a comment

It doesn’t look pretty, but if you really wanted to embed a link in your rails flash response you could do it like this:

      flash[:success] = "Foo. #{ActionController::Base.helpers.link_to "Create new listing", '/listings/new'}".html_safe

Couple other options can be found here:

How to add a boolean column to a table in rails

Leave a comment

As a reminder to myself, here are some notes on how to add a boolean column to a table in rails3.

Step 1: Create migration

rails generate migration add_public_to_listings admin:boolean

Step 2: Write unit tests on model


    describe "admin attribute" do

      before(:each) do
        @listing = @user.listings.create!(@attr)

      it "should respond to public" do
        assert_respond_to(@listing, :public)

      it "should not be public be default" do
        assert !@listing.public

      it "should be converible" do
        assert @listing.public

Step 3: Update test data


def make_listings
  puts "----------------"
  puts "--- listings ---"
  puts "----------------"

  myUser = User.find_by_email("")

  ls1 = myUser.listings.create!(:title => "The Mona Lisa",
                               :description => "Master peice",
                               :category_id => 2,
                               :address => "T3H0E2",
                               :location => "Calgary, Alberta, Canada")

Note: We set the :public value through the toogle for security reasons. Only those variables exposed via attr_accessible

class Listing < ActiveRecord::Base
attr_accessible :title, :description, :category_id, :address, :location

can be set through mass assignment. This prevents bad guys from changing values like this:

put /listings/17?public=1

Thanks again Michael for the great example.

Rails TimeRange

1 Comment

Say you want to query your backend objects with a range of times.

One way to do that is to define a TimeRange object which captures the time ranges you are interested in:


class TimeRange

  def self.yesterday
    ( -

  def self.last_week

  def self.ages_ago

And then using these to define your ‘created_at’ parameter:


    case params[:date_posted]
    when 'today'
      created_at =
    when 'yesterday'
      created_at = ( -
    when 'last week'
      created_at = (
    when 'ages ago'
      created_at = (
      logger.error "Unknown posted date on listings search #{params[:date_posted]}"

which can then be used in your search:

    @attr = {
            :location => @location,
            :category_id => params[:category_id],
            :created_at => created_at

    @listings = Listing.where(@attr)

Not bad!

See my previous post here for where to place your TimeRange object and how to reference it from another ruby class.

How to reference domain classes in rails

1 Comment

Working with active records in rails is nice because a lot of your domain is directly represented in your model classes.

Sometimes however, you still need to create some domain classes that aren’t tied to a database model, and reference them in your app.

I’m not sure what the best way (or convention) is for doing this, but what’s been working for me is to create a separate directory called domain

and place my domain object(s) in there:

class TimeRange

  def self.yesterday
    ( -

  def self.last_week

  def self.ages_ago

And then referencing them where I need them using the ‘require_relative’ command.

require_relative '../domain/time_range'
require_relative '../domain/constants'

class CitiesController < ApplicationController

How to drop, create, populate, and reset your rails database

Leave a comment

Getting frustrated with all the commands I needed to type I created the following scripts and tools to simplify destroying and recreating my rails database.

Step 1: Create an ‘all’ task.


namespace :db do

  task :all => [:environment, :drop, :create, :migrate, :populate] do


The basic commands for recreating and populating your database from the command line often require some variation of:

Rebuild db
$ rake db:drop
$ rake db:create
$ rake db:migrate
$ rake db:fixtures:load RAILS_ENV=test
$ rake db:test:prepare

This rake task does most of this for us. To get data into the database I create a second task shown above ‘populate’.

Step 2: Create a populate task.

require 'faker'

namespace :db do

  desc "Fill database with sample data"
  task :populate => :environment do

    puts "----------------"
    puts "RAILS_ENV is #{RAILS_ENV}"
    puts "----------------"

    puts "----------------"
    puts "--- populate ---"
    puts "----------------"



def make_cities

  puts "----------------"
  puts "--- cities   ---"
  puts "----------------"

  City.create!(:name => "Calgary")
  City.create!(:name => "San Francisco")

def make_users

  puts "----------------"
  puts "---- users  ----"
  puts "----------------"

  admin = User.create!(:name => "aaa",
                       :email => "",
                       :password => "foobar",
                       :city_id => 1)
  2.times do |n|
    name =
    email = "example-#{n+1}"
    password = "password"
    User.create!(:name => name,
                 :email => email,
                 :password => password,
                 :city_id => 1)

This task uses the fake gem to create and load test data into which ever environment we pass in via ‘RAILS_ENV’. It won’t work by itself yet, but we can now run this using our ‘all’ task by going:

> rake db.all
> rake db.all RAILS_ENV=test

Step 3: Put it together in a bash script

echo "Reseting database"
rake db:all
rake db:all RAILS_ENV=test

Now when ever I would to scrap and start all over, I rollback my git repository, and rebuild my db.

Voila. Clean slate and I can what ever it was I was trying to do again.

How to setup Jasmine Rails31 directory structure

Leave a comment

Following are instructions on how to setup/configure jasmine for use with rails31. It’s mostly straight forward, just one gotcha with regards to how to tell jasmine where your source files are.

1. Add jasmine gem has a nice summary of how to setup and install the rails gem for jasmine.


gem 'jasmine', :group => [:development, :test]

> bundle install
> rails g jasmine:install
> rake jasmine

2. Create your test.


describe("ListingModelSpec", function() {

  beforeEach(function() {
    setFixtures('<input type="hidden" id="city_name" value="Calgary" />');

  it("gets the city name", function() {
    var model = new ListingsModel();


Here I am writing a test that verifies I can read a value from a hidden field. To do that, jasmine will need jquery, and another useful helper library called jasmine-jquery (for that setFixture method).

Download and place them both in the /spec/javascripts/helpers dir.

4. Tell jasmine where to find your javascript files.

jasmine knows where to find your src files via it’s jasmine.yml file.

Assuming you want your javascript files to live under apps (where rails31 like them)

Edit the jasmine.yml file to look something like this:


# src_files
# Return an array of filepaths relative to src_dir to include before jasmine specs.
# Default: []
# src_files:
#   - lib/source1.js
#   - lib/source2.js
#   - dist/**/*.js
  - public/javascripts/prototype.js
  - app/assets/javascripts/**/*.js

See that last line at he bottom? That’s the one you need to point to the rails3 javascript directory. The other files above it points to where rails used to share it’s javascript files but everything is now stored under apps so just point there.

With that you should now be able to run your own javascript tests by firing up the jasmine server:

> rake jasmine

Going to localhost:8888 and seeing your output there.

More resources

Older Entries

%d bloggers like this: