Ruby on Rails Quick Reference

This Quick Reference guide is designed to only contain the Ruby on Rails
commands, syntax, and methods that are used in the majority of
applications, arranged by “What do you need to accomplish?”
This isn’t meant to be a complete guide to every single part of Rails,
it’s more a list that I’ve created for myself. It’s a work-in-progress,
and will continually change until I feel that it covers enough topics.
If you are interested in knowing when it will change, you can subscribe
to my blog feed.

Creating a Rails Application  
rails project_name –database=sqlite3
a rails application, the -database option lets you choose
somethin gother than the default, which is MySQL.
Freeze Rails Version  
command will “freeze” your app at the current version. This is
very useful if you are on a shared hosting server and your provider
likes to upgrade to every little release without even mentioning that
they are going to break your application. Sure, there was a security
problem, but they could at least have sent out proper notifications.
Me, bitter? never!
Upgrade / Configure your
This is very useful when you or your provider upgrades a
version. You may not use this in development, but you will definitely
use this over time, see above)
app, scripts in public / javascripts directory
the built-in rails javascript (prototype / scriptaculous ) to
the latest version
the application scripts ( generators, etc )
out your logfiles
out the sessions table, especially useful during testing, or if
you are upgrading an application where you’ve made changes to model
objects you store in the session.
reload! Use this from within script/console to reload the
application. This is extremely useful when you make changes, so you
don’t have to constantly exit/open the console to see your new changes.
Creating new tables / migrations  
Update database schema to next
rake db:migrate VERSION=x Update database schema to a past
version “x”, like VERSION=4
ruby script/generate model Itemname Create everything needed for a new
table in your app. Make sure you use
the singular form here! It will generate a migration file in db\migrate
named according to your model object, which you will use to generate
the new database table.
rake db:sessions:create Create everything needed to store
sessions in the database.
= :active_record_store
Uncomment this line in
/config/environment.rb to make sessions use the
:articles do |t|
t.column :title, :string
t.column :created_at, :date
this code to the self.up method in your /db/migrate/00x_migratename.rb
files to add new tables.
add_column :tablename, :fieldname, :integer Add a column “fieldname” to table tablename. Add this
code to the self.up method in your migration file.
remove_column :tablename, :fieldname Remove the column “fieldname” from table tablename. Add
this code to the self.down method in your migration file.
change_column :tablename,
:fieldname, :integer
Change the column according to the
column options, be very careful with
this command, because you can get errors if you try to convert strings
to integers, for instance.
/ Database Field
Table Name: Parents All tables must be in the plural
Primary Key: id Every table must have a column named
id as the primary key.
Table Name: Children Plural forms like Children are
supported in Rails, even though they
don’t have the traditional (s) at the end.
Foreign Key:
parent_id (singular_id)
When joining tables, you must use a
field named in the singular form
with _id. For instance, if joining the Parents table, ActiveRecord will
look for a field named parent_id and attempt to join it to the field.
Create fields named either one of
these names in your table, and
ActiveRecord will automatically timestamp whenever a modification is
Create fields named either one of
these names in your table, and
ActiveRecord will automatically timestamp them on initial row create.
/ Model Validation
  All of these need to be added into
your model object for the validation
to work. I would highly suggest using validation on all your objects on
any field that really should contain a value. For instance, if you have
a title or name field on your objects, chances are you’ll need a value
in it for your application to work. Use validation, it’s easy!
  All validations take the extra options :message and :o n, which are in some of the examples below.
validates_presence_of :title,
the existence of whatever values you pass to it. In this case, title
and description.
validates_length_of :password, :minimum
=> 8,

:message=>”should be at least 8 characters, Idiot.”

Check for the length of the :fieldname field, in this
case the password.
validates_acceptance_of :eula, :accept=”yes”, :o n=>:create Ensure that the user has selected the “yes” option on
the eula field. The :o n option signifies that this will only happen on
create, not update
validates_confirmation_of :password This validation makes sure that if a field
:fieldname_confirmation is passed into the model object along
with the field :fieldname, that the two fields match. This
would potentially be used to validate the email address as well, in a
form where you have to enter your email address twice. For
email it would obviously be :email and :email_confirmation
validates_numericality_of :numberfield Validate that it’s a number. Kinda simple.
validates_inclusion_of :fieldname, :in => %w(
yes, no )
Validate that a field is in an enumeration list. This
is useful if you have a hard-coded dropdown list of some type, or for
validating that data in a list wasn’t manipulated on the client.
validates_exclusion_of ( see above) Exact opposite of the above
ruby unit/test/unitname_test.rb Run a single unit test. Very useful for when you are
writing tests, as it takes the least amount of time.
rake test Tests everything, takes longer, probably more useful
for automated or daily tests
rake test:units Runs unit tests. These consist of tests for your model
objects, housed in /test/unit/
rake test:functionals Functional testing are the tests that check your
controllers, actions, views, etc. This command will run all of those
rake test:integration Integration tests allow you to simulate a dry run
through your application. This command will run all integration tests.
rake test:recent This command will test recently modified tests.
ActiveRecord / Lists of Items  
has_many :childitems, :o rder=>:position If
you want to make your sub-items support auto-positioned lists, just add
an integer column called position to your child table, and then add
this to
the parent model class. In this case childitems is the child table.
acts_as_list Add this to your child model class.
Childitem.move_lower Move an item down in the position.
If it was position 2, it will now be
position 3
Childitem.move_higher Move an item down in the position.
If it was position 3, it will now be
position 2
Childitem.move_to_top Move an item to the top
Childitem.move_to_bottom Move an item to the bottom
Installation of acts_as_taggable plugin. See my article on tagging
with full text search, which contains information on
installation of this plugin.
Item.tag_with(“plugin awesome easy”) Add the three tags to the Item
Item.find_tagged_with(“awesome”) Find any Item class tagged as
Item.tags_count(:limit=>100, :o rder=>”count desc”) Get the top 100 tags, ordered by
the count of the number of times the tag was used. you can also order
by name instead if you want.
xml.element_name do
… put stuff here ….
xml.element_name do
xml.another(“valuehere”, “the


  Note: You can use regular “for @val
in @list” syntax within the rxml
“Total: #{}”
Replace the element “elementname”
with the text “Total: 12″ (
or whatever is equal to )
:highlight, :startcolor
=> “#939923″, :endcolor => “#FFFFFF”
Make the element “elementname” flash
from one color to another. Useful
for noting that an item has been changed on the page, like a shopping
cart total, or a rating box like on Digg.
Use to make elementname look like
it’s disappearing
Use to make elementname look like
it’s appearing
:partial => ‘news’, :o bject
=> @news
Replace the element ‘elementname’
with the rendered partial. This is
most useful for when you are updating a partial template that you had
previously rendered inline in the page. For instance, if you had a
“News” partial, and your ajax call wants to add a new item into the
News section, you’d just re-render the news partial and replace it. Of
course, you’ll need to grab the latest news on your controller action
into the variable @news for that to work.
Hashes, Data objects
@hashlist = Item.find(:all).map{ |i|
i.fieldname }
Make a hashlilst of just a
particular field, will return dupes
@hashlist = Item.find(:all).map{ |i|
i.fieldname }.uniq
Adding .uniq to the end returns a
unique list. kinda like a select
distinct in sql
@matches ={ |i| i
== value }
Returns a new array wherever it
matches value. could be any comparison
( i > 0 , etc)
@matches ={|i|
i.fieldname == “blah” }
Returns a new array where the
fieldname matches.
@matches ={ |i|
i.totalsales > 1000 }.map{|i|
Returns a distinct array containing
just the names of the customers
that have totalsales of more than 1000.
/ Views
<% render
:partial=>”partialname” %>
Will render the partial named ”
_partialname.rhtml ” in the same
directory as the current controller
<% render
:partial=>”home/partialname” %>
Will render the partial named ”
_partialname.rhtml ” in the home view
:partial=>”partialname”, :layout=>true
Renders the partial inside the
regular layout. You’d use this in a
controller when you just want to display a form or something,but not
need to bother with a whole page for that action.
<%= url_for
:action=>”actionname”, :o nly_path=>true %>
Will give you just the url
/controllername/actionname/ , without the
full servername.
<% link_to
“linktext”,:action=>:theaction %>
link. Duh.
h(@variable_to_strip_html) Remove html chars before output.
Should always do this on text fields
being outputted to the screen.
<% for @item in @itemlist %>

<li><%=@item.fieldname %></li>
<% end %>

quick list of the items in @itemlist
Creates an ajax form tag. The only
difference in an Ajax form is that
you use _remote in it, instead of form_tag. Very simple!
<%=submit_tag “Click!”
Same as a regular button
<%=end_form_tag %> End the form tag, just like a normal
/ Edit in Place
in_place_edit_for :item, :title Add this line to the controller to
automatically wire up the save
actions for the title field on the item class.
<%= in_place_editor_field
:item, :title,{}, :rows=>10
Use this line in your template to
insert the edit in place “control”.
Note that the last two options are optional. Omitting them will make a
standard textbox.
input[type="text"] {
Use this line in your stylesheet to
customize the width of the default
edit in place text editor field using CSS.
Fun Stuff  
rake stats Gives you stats on your code like lines of code, number
of classes, etc.

7 Responses to “Ruby on Rails Quick Reference”

  1. Justin - C2 Global Technologies Says:

    What is

  2. Anthony Ettinger Says:

    @Justin: that escapes html.

    Great reference for improving my ruby chops :)

  3. Jennifer C Says:

    Bookmarked. Thanks.

  4. Rusty Says:

    What is the difference between created_on and created_at? Is one for date and one for time? Is there a way to get that as one :datetime? How is this time stamping different from the :timestamp column type? The documentation is pretty vague…

  5. felix Says:

    i am trying to save 5 text_field value in one field using ROR.what is the coding of it

  6. Dallas Ray Says:

    I had started to make some flash cards with this type of stuff… but then I found your list. Thanks so much!

  7. Piyush Says:

    NIce one …… :-)