Ruby on Rails Quick Reference
Wednesday, December 27, 2006
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 rails project_name –database=sqlite3 |
Create a rails application, the -database option lets you choose somethin gother than the default, which is MySQL. |
| Freeze Rails Version | |
| rake rails:freeze:gems |
This 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 application |
(Note: 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) |
| rake rails:update |
Updates app, scripts in public / javascripts directory |
| rake rails:update:javascripts |
Update the built-in rails javascript (prototype / scriptaculous ) to the latest version |
| rake rails:update:scripts |
Updates the application scripts ( generators, etc ) |
| rake log:clear |
Clears out your logfiles |
| rake db:sessions:clear |
Clears 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 | |
| rake db:migrate |
Update database schema to next version |
| 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. |
| config.action_controller.session_store = :active_record_store |
Uncomment this line in /config/environment.rb to make sessions use the database |
| create_table :articles do |t| t.column :title, :string t.column :created_at, :date end |
Add 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. |
| ActiveRecord / Database Field Names |
|
| Table Name: Parents | All tables must be in the plural form. |
| 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 Parents.id field. |
| updated_at updated_on |
Create fields named either one of these names in your table, and ActiveRecord will automatically timestamp whenever a modification is made. |
| created_at created_on |
Create fields named either one of these names in your table, and ActiveRecord will automatically timestamp them on initial row create. |
| ActiveRecord / 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 :on, which are in some of the examples below. |
|
| validates_presence_of :title, :description |
Automatically validate 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”, :on=>:create |
Ensure that the user has selected the “yes” option on the eula field. The :on 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 |
| Unit Testing |
|
| 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 tests |
| 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, :order=>: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 |
| acts_as_taggable Plugin |
|
| 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 class. |
| Item.find_tagged_with(”awesome”) | Find any Item class tagged as “awesome” |
| Item.tags_count(:limit=>100, :order=>”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. |
| RXML Templates |
|
| xml.element_name do end |
<element_name> … put stuff here …. </element_name> |
| xml.element_name do xml.inner_element(”valuehere”) xml.another(”valuehere”, “the attribute”=>”value”) end |
<element_name>
<inner_element>valuehere</inner_element> |
| Note: You can use regular “for @val in @list” syntax within the rxml template. |
|
| RJS Templates |
|
| page[:elementname].replace_html “Total: #{@item.total}” |
Replace the element “elementname” with the text “Total: 12″ ( or whatever @item.total is equal to ) |
| page[:elementname].visual_effect :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. |
| page[:elementname].visual_effect :blind_down |
Use to make elementname look like it’s disappearing |
| page[:elementname].visual_effect :blind_up |
Use to make elementname look like it’s appearing |
| page[:elementname].replace_html :partial => ‘news’, :object => @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. |
| Arrays, 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 = @hashlist.select{ |i| i == value } |
Returns a new array wherever it matches value. could be any comparison ( i > 0 , etc) |
| @matches = Item.select{|i| i.fieldname == “blah” } |
Returns a new array where the fieldname matches. |
| @matches = Item.select{ |i| i.totalsales > 1000 }.map{|i| i.custname}.uniq |
Returns a distinct array containing just the names of the customers that have totalsales of more than 1000. |
| ActionController / 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 directory |
| render :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”, :only_path=>true %> |
Will give you just the url /controllername/actionname/ , without the full servername. |
| <% link_to “linktext”,:action=>:theaction %> |
A link. Duh. |
| Text Formatting |
|
| h(@variable_to_strip_html) | Remove html chars before output. Should always do this on text fields being outputted to the screen. |
| <ul> <% for @item in @itemlist %> <li><%=@item.fieldname %></li> |
A quick list of the items in @itemlist |
| Ajax Forms |
|
| <%=form_remote_tag :url=>{:action=>:blah}%> |
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 form. |
| Ajax / 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. |
| .inplaceeditor-form input[type=”text”] { width:350px; } |
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. |
April 30th, 2007 at 8:47 am
What is
h(@variable_to_strip_html)!
May 11th, 2007 at 10:19 pm
@Justin: that escapes html.
Great reference for improving my ruby chops :)
June 11th, 2007 at 1:51 pm
Bookmarked. Thanks.
June 17th, 2007 at 7:54 pm
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…
June 28th, 2007 at 5:49 am
Great reference for improving my ruby chops :)
For Ajax see : www.blog.aioapps.com
July 30th, 2007 at 8:34 pm
hai,
i am trying to save 5 text_field value in one field using ROR.what is the coding of it
November 26th, 2007 at 2:09 pm
I had started to make some flash cards with this type of stuff… but then I found your list. Thanks so much!
December 12th, 2007 at 1:52 am
NIce one …… :-)
January 12th, 2008 at 1:08 am
Nice Article.
Regards,
Deepak Kalhan
(www.aioapps.com)
June 10th, 2008 at 7:08 am
Really nice article and since I am starting to get hands on RoR this will be really helpful.