Ruby on Rails Cheat Sheet


Loop through an array:

array.each do |var|
  print var 


Don’t forget that all member variables assigned via a form need to be listed under attr_accessible:

attr_accessible :first_name, :last_name

There are many validations available:

validates :column, :presence => true
Validates that a column isn’t blank
validates :column, :numericality =>true
Validates that the user entered a number
validates :column, :length => {:maximum => 10, :minimum => 5}
Validates that the text that was entered was at least 5 but no more than 10 letters long. You don’t need to specify both :maximum and :minimum; only one is required.
validates :column, :inclusion => {:in => 100..200}
Validates that the number entered is between 100 and 200
validates :column, :exclusion => {:in => %w( TISM Journalism) }
Validates that the user did not enter the string TISM nor the string Journalism. Note that this is case sensitive; capitalization matters.


Variables passed in a form can be accessed with params[:variable_name]

@first_name = params[:first_name]

You can put the list of objects in order with order():

@people = Person.order(:last_name).all

You can redirect the user to a different page with redirect_to <url>:

redirect_to people_url


You can view all of your current routes, with their names, using the command rake routes.


There are 7 standard actions for a resource:

Action Supposed to do URL URL function Method
new Displays form for a new preson /people/new new_person_url  
create Saves a new person to DB /people people_url :method => :post
index Displays list of all people /people people_url  
show Displays a single person /people/5 person_url(@person)  
edit Displays for to edit a person /person/5/edit edit_person_url(@person)  
update Saves new data for existing person /people/5 person_url(@person) :method => :put
destroy Deletes a person from DB /people/5 person_url(@person) :method => :delete