Ruby on Rails Cheat Sheet – Handy Tips Gleaned from RoR Tutorial Book

Every time I go away from RoR for a while, I forget everything I had learned. In order to get me up to speed more quickly in the future, I am going to create a Ruby on Rails cheat sheet that describes how to accomplish simple tasks with Rails.

These tips all come from the Ruby on Rails Tutorial by Michael Hartl and the section #s below refer to it (http://ruby.railstutorial.org/book).

Create static pages (3.1.2):

Tell generate to use RSpec:

rails generate rspec:install

Generate static pages:

// generates home and help pages
rails generate controller StaticPages home help --no-test-framework

 Undoing generate commands

// Example
rails generate controller FooBars baz quux
rails destroy  controller FooBars baz quux
// Example 2
$ rails generate model Foo bar:string baz:integer
$ rails destroy model Foo
// Rake db:migrate example
rake db:migrate
rake db:rollback

Everything in Ruby (even a string and nil) is an object (4.2.3)

nil.to_s
=> ""
"foobar".empty?
=> false

 Array operations followed by a bang (!) affect the array (4.3.1)

>> a
=> [42, 8, 17]
>> a.sort
=> [8, 17, 42]
>> a
=> [42, 8, 17]
>> a.sort!
=> [8, 17, 42]
>> a
=> [8, 17, 42]

You can think of symbols as basically strings without all the extra baggage (4.3.3)

>> user = { :name => "Michael Hartl", :email => "a@b.com" }
=> {:name=>"Michael Hartl", :email=>"a@b.com"}
>> user[:name]       # Access the value corresponding to :name.
=> "Michael Hartl"

Alternate syntax for using symbols as hash keys (4.3.3):

>> h1 = { :name => "Michael Hartl", :email => "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}
>> h2 = { name: "Michael Hartl", email: "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"} 
>> h1 == h2
=> true

Adding Bootstrap and Sass (5.1.2)

  1. Make sure the bootstrap gem is listed in your gemfile
    gem 'bootstrap-sass', '2.0.4'
  2. Create a Sass file (app/assets/stylesheets/custom.css.scss) with the following line
    @import "bootstrap";
  3. That’s it!

Creating and referencing partials (5.1.3)

  1. File name and location:
    app/views/layouts/_partial_name.html.erb
  2. Reference to partial:
    <%= render 'layouts/partial_name' %>

 Asset directories and their purposes (5.2.1)

  • app/assets: assets specific to the present application
  • lib/assets: assets for libraries written by your dev team
  • vendor/assets: assets from third-party vendors

Each has images, javascripts, and stylesheets subdirectories.

Routes to static pages (5.3.2)

The following line redirects /help to the help.html.erb layout in the static_pages directory

match '/help',    to: 'static_pages#help''

It also creates the following two named routes:

about_path => '/about'
about_url  => 'http://localhost:3000/about'

Creating a controller (5.4.1)

# Creates a simple "new" view and empty "new" controller method
# --no-test-framework prevents creation of initial testing spec
rails generate controller Users new --no-test-framework

Creating a model (6.1.1)

rails generate model User name:string email:string

 Annotating model definitions with details from their DB counterparts (6.1.2)

# Add gem to Gemfile (only for development)
gem 'annotate', '2.5.0', group: :development
# Goes through DB tables and comments corresponding model files
bundle exec annotate

 Test Driven Development (3.2.1, 6.2.1)

  • Create a ‘request’ test for each static page (/spec/requests/…)
  • Create a model test for each model (/spec/models/…)

Adding migrations to an existing model (6.2.5)

rails generate migration add_index_to_users_email

Look for the new migration file and edit it appropriately. Then run:

bundle exec rake db:migrate

Example #2 (specifying a column to add to a table):

rails generate migration add_password_digest_to_users password_digest:string

Post migration creation:

$ bundle exec rake db:migrate
$ bundle exec rake db:test:prepare
$ bundle exec rspec spec/

Also, use add_index (8.2.1) to create an index on any column that will be used to retrieve info

Add debug info to a view (7.1.1)

<%= debug(params) if Rails.env.development? %>

Run console in a different environment (test/development/production) (box 7.1)

rails console test

Run server in a different environment (test/development/production) (box 7.1)

bundle exec rake db:migrate RAILS_ENV=production

Reset the database (7.2)

bundle exec rake db:reset

# "ensures that the data model from the development database is reflected in the test database" 
bundle exec rake db:test:prepare 

[restart Web server]

Completely clear and reset the data base (http://bit.ly/RL1HN1)

rake db:drop
rake db:create
rake db:migrate

Run a subset of rspec tests matching a string (7.4.4)

rspec -e "signup page"

Deploy to Heroku (7.4.4)

1. git push heroku
2. heroku run rake db:migrate
3. heroku open (opens the site in a browser)

Reset a Heroku DB (9.5)

$ git push heroku
$ heroku pg:reset HEROKU_POSTGRESQL_CHARCOAL_URL [probably]
$ heroku run rake db:migrate
$ heroku run rake db:populate

Making error messages more user friendly (7.6)

Flash messages vs. flash.now messages (8.15)

  • flash messages stay on the screen for one request (ex: redirect)
  • flash.now messages for one render. Goes away on next request.

Note about helpers

  • By default, all the helpers are available in the views but not in the controllers
  • So, it is necessary to explicitly include helpers within controllers

Cool shortcut to finding objects by a property (8.2.3 and elsewhere)

Object.find_by_property("str")
ex: User.find_by_name("Joel B")
ex: User.find_by_email("jberghoff@yahoo.com")

 Writing tests for checking cookie values (not a great idea) (8.2.6)

… experience shows that direct tests of cookie values are brittle and have a tendency to rely on implementation details that sometimes change from one Rails release to the next. The result is breaking tests for application code that still works fine. By focusing on high-level functionality—verifying that users can sign in, stay signed in from page to page, and can sign out—we test the core application code without focusing on less important details.

Visiting a typical page with RSpec:

before { sign_in user }

Visiting a path involving an update with RSpec (9.2.1)

before { put user_path(user) }

Note that direct use of the PUT HTTP request here. There’s no other way to do it.

Using exclamation points with actions (9.3.2)

  • create will return “false” if it doesn’t work
  • create! will raise an exception if it fails

Populating the DB with sample users (see section 9.3.2)

Adding a boolean field to a db table = awesome (9.4.1)

1. $ rails generate migration add_admin_to_users admin:boolean
2. Creates
      class AddAdminToUsers < ActiveRecord::Migration
        def change
          add_column :users, :admin, :boolean, default: false
        end
      end
3. Change line to: add_column :users, :admin, :boolean, default: false 4. This automatically creates test user.admin? test

Only attr_accessible attributes can be assigned through mass assignment (9.4.1)

A note about arrays in Ruby (10.1.4)

Array assignment in Ruby copies a reference to the array, not the full array itself, which means that changes to the original array also affect the copy.

One thought on “Ruby on Rails Cheat Sheet – Handy Tips Gleaned from RoR Tutorial Book

  1. Pingback: Ruby on Rails Cheat Sheet Part 2 - More Tips and RemindersBlog de Code

Leave a Reply