Saturday, August 16, 2008

Rails Tutorials

Here are a few beginner tutorial about Ruby on Rails:

  • has_many :through tutorial by byrnejb: "What I want to do is have three tables: movies, dancers and their join table that I called dancer_movies. The main goal of this exercise is to be able to add dancers directly via a drop down that lists all dancers from the database (and the number of dances they appeared in in that movie) when creating a new movie entry."
  • Rails 2.1 Tutorial by Tutorials Point.
  • Ruby on Rails Tutorial on Rails Wiki to get a basic Rails application running.
  • Tutorial on using the Ruby MySQL Module by Paul Dubois.
  • Hpricot interface to using Libxml. Hpricot is a user friendly XML parser for Ruby but Libxml is blazing fast. This tutorial shows how you can implement a hpricot like interface to using libxml.
  • Parsing XML with Ruby: This tutorial by John Nunemaker shows how you can parse XML using Hpricot, libxml and REXML. Example parsing of Twitter and feeds is shows.
  • REXML tutorial for parsing XML
  • Parsing XML using Ruby: A tutorial by Yahoo

Labels: , , , , , , , ,

Back to Ruby

My apologies to readers of this blog for not posting on this blog for more than a year. Since June 2006, I was working for the 13th largest website in the world (based on traffic) with more than 4 billion page views a month. There was little to no use of Ruby at my previous employment as it was primarily a Java shop. I gained a lot of scalability experience working for them. In July of this year, I left my job to join a very promising new startup that's working on a disruptive technology (more on this later).

One of the good things about my new job is that we are primarily a Ruby shop, so you can definitely expect more postings :).

Labels: ,

Tuesday, December 05, 2006

Displaying a Textarea field

Use the following in your views to add a text area control.
text_area 'portal', 'portal_description' , :rows=>4, :cols=>40 

Displaying a DATE TIME field

If your column is defined to be DATETIME, then you can use the datetime_select method to display the date/time control.

datetime_select 'subscription', 'created_at' 

The default date and time values for this control can be specified. See setting the default time for datetime_select.

For more information see datetime_select manual page.

Saturday, October 07, 2006

I wanted to allow a user to type in the address for their community and then instantly inform them whether the address they wanted was available.

In my controller:

def check_portal_url

In my view:

<%@comm = Portal.find_by_portal_url(@params[:search]) %>
<%if @comm%>
<%=@params[:search]%> is taken, please try a different address.
<%=@params[:search]%> is available.

and in my form

<%= observe_field(:portal_portal_url,
:frequency => 0.5,
:update => :observe_results,
:loading => "'spinner')",
:complete => "Element.hide('spinner')",
:url => { :controller=>'ajax',:action => 'check_portal_url' },
:with => "'search=' + escape(value)"
) %>

<div id="observe_results"></div>
In the above, the
                :with => "'search=' + escape(value)"

part is very important as without it, the value of the field will be very hard to access.

Monday, August 21, 2006

LIKE as a condition to get records.

Here's a handy tip for Rails beginners: When you need to find records based on a condition that involves the use of LIKE '%value%' (it's going to be very slow since MySQL won't use an index for this query), try something like the following:

 @records = MyModel.find(:all, :conditions => ['col LIKE ? ', '%'+@term+'%'],:limit => 10)

Starting Webrick on a different port

Often you may need to start webrick on a different port. Luckily, you can do so using the -p options.

[root@srv31 ror]# ruby script/server -p 9191
=> Booting WEBrick...
=> Rails application started on
=> Ctrl-C to shutdown server; call with --help for options
[2006-08-21 13:45:37] INFO WEBrick 1.3.1
[2006-08-21 13:45:37] INFO ruby 1.8.4 (2005-12-24) [i686-linux]
[2006-08-21 13:45:37] INFO WEBrick::HTTPServer#start: pid=4812 port=9191

For more help options use the --help option:

[root@srv31 ror]# ruby script/server --help
=> Booting WEBrick...
Usage: ruby server [options]

-p, --port=port Runs Rails on the specified port.
Default: 3000
-b, --binding=ip Binds Rails to the specified ip.
-e, --environment=name Specifies the environment to run this server under (test/development/production).
Default: development
-m, --mime-types=filename Specifies an Apache style mime.types configuration file to be used for mime types
Default: none
-d, --daemon Make Rails run as a Daemon (only works if fork is available -- meaning on *nix).
-c, --charset=charset Set default charset for output.
Default: UTF-8

-h, --help Show this help message.

Sunday, August 06, 2006

ActiveRecord::Subclass Not found

If you ever get the following error:

The single-table inheritance mechanism failed to locate the subclass: 'link'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Olink.inheritance_column to use another column for that information.

Make sure you don't have a field named type in your table.

Saturday, July 29, 2006

Comparison of String with Integer failed

If you have code like

if @category_id >=1

then you will get the following error:

comparison of String with 1 failed

To fix the error modify the above code so it is something like:

if @category_id.to_i >=1

Custom URLs with routes.rb

Using the routes.rb file, we can create custom URLs. It is important to note that the following is valid :

map.connect ':permalink', :action=>'list', :controller=>'categories'

whereas the following are not valid:

map.connect ':permalink-:id', :action=>'list', :controller=>'categories'
map.connect ':permalink_id.html', :action=>'list', :controller=>'categories'
map.connect ':permalink-:id.html', :action=>'list', :controller=>'categories'

Calling a controller method from a view raises NoMethodError

If you put a custom function in application.rb or another controller and then try to access it from your view, you'll get the "No Method Error" similar to following:

NoMethodError in Categories#list
Showing app/views/categories/list.rhtml where line #23 raised:
undefined method `create_permalink' for #<#:0xb7931838>

The solution is to place the function as a helper function in the app/helpers/categories_helper.rb or app/helpers/application_helper.rb file.

URL Escape and URL Unescape

I find these functions really handy when having to escape or unescape URL:

def url_escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase' ', '+')

def url_unescape(string)'+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do

I usually place them in application.rb.

Calculating time difference

Here is a Ruby on Rails function I wrote that returns time difference in minutes. It can be easily modified to return time difference in seconds, hours etc.

def time_diff_in_minutes (time)
diff_seconds = ( - time).round
diff_minutes = diff_seconds / 60
return diff_minutes

Embedding and extracting primary key in a clean URL

Clean URLs are very important for search engines and for that reason I always prefer them.

A url of the form is better than

An even better form of the URL is where article-title represents the important keywords that appear in the title.

When using Ruby on Rails, you can create the permalink from title using the following function:

def create_permalink(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase' ', '-').downcase


and you can extract the id from this permalink using a function given below:

def get_id_from_permalink(permalink)
@temp_array = permalink.split('-')
return id

Sunday, July 16, 2006

Ruby on Rails tips

Call a function before each method in a controller.
Define the function in application.rb and then edit your desired controller file and put the following
before_filter :application_essentials

Wednesday, April 12, 2006

Rails Optimization

Today I came across a good article about Ruby on Rails optimization on Text Drive by Julik. She talks about the various steps you can take to optimize your Rails application. While you really should read the article, in a nutshell, she talks about the following:

1. Minimize the amount of FCGI listeners
2. Use caching
3. NEVER run “development” on FastCGI for more than 1-2 hours
4. Observe your memory consumption
5. Rotate your logs
6. Write and run unit tests
7. Check for memory leaks when you are developing
8. Be careful with iterations
9. Watch the Rails TRAC for bug reports
10. Be vigilant when restarting your server

I will add more Rails related optimization resources in the future and post them to my Ruby on Rails favorites so check back soon.

Lite Speed web server: I haven't checked Lite speed web server yet, but plan to do so very soon.


Thursday, March 23, 2006

To Open Source or Not to Open Source?

I have been receviving a lot of feedback on and based on the feedback, I have one question:

Should I open source my project? What are benefits / drawbacks?

Adoppt employs many principles that I have learned over the years. Alongwith my upcoming Pro Rails book, it will be something nice to give back to the community.

So far I think I would like to Open Source the software only for personal use and place a licensing fee for commercial use. Is that possible with Open Source? I know MySQL does something like this.

If I do Open Source it, should I host the code myself or put it on Sourceforge or Rubyforge?

Questions / Ideas / Experiences / Suggestions Welcome


MVC - Model View Controller Architecture

Here's a diagram I made to help explain MVC architecture to beginners.

If the Model, View Controller (MVC) terminology bothers you, you may use the alternate vocabulary until you can feel comfortable. For instance, as depicted in the figure above, you may refer to "controller" as "input", "model" as "processor" or "processing" and "view" as "output".

So in other words, controller receives the input, passes it to the model for processing, or to the view for output.


Tuesday, March 21, 2006

What the people want

These are some questions I have received about what people want to learn about Ruby on Rails, after I asked what people were interested in a post made yesterday to my MySQL blog entitled, Pro Rails and Applied Ruby on Rails: What do you want to learn? Please don't hesitate to send me your own questions and topics about Ruby, Ruby on Rails, and AJAX you would like to see covered in my upcoming book Pro Rails and Applied Ruby on Rails. Send questions to softwareengineer99 at yahoo dot com.

· How to install rails
· How to start an application
· What should I be familiar with before starting?
· How to install plugins (gems)
· How long will it take me to learn
· how to make a blog application
· how to make a forum application
· how to make a messaging system
· how to make a tagging system
· what if I don’t know OO?
· Is ROR different than Ruby?
· How do I connect to databases in Ruby OR
· What databases can I use with ROR?
· How do I paginate documents in ROR
· How do I made a class?
· What is a class?
· What are attributes?
· What are variables?
· What are functions?
· What is MVC
· What are models?
· What are views?
· What are controllers?
· How are they used together?
· How do I validate things in ROR?
· What is HABTM?
· will my application work on multiple browsers
· can I use ROR on a Mac? Windows? Linux?
· Can I scale my application?
· What are normalized tables
· How do I make normalized tables?
· can I use ROR with more than one database?
· how do I use AJAX with ROR
· What is AJAX?
· What is Ajax used for?
· Is there a ROR community to turn to for help?
· What is a Rails Engine?
· How can I use a Rails Engine?
· Do I need special hosting service to have a ROR application on the web?
· What are some tools I can use to learn ROR?
· What are some good websties about ROR?
· What port does ROR run on?
· Can I use ROR with apache?
· Can I use ROR with lighttpd?
· What are relationships?
· What is a many to many relationship?
· What is a one to many relationship?
· Where would I use a JOIN?
· How can I search and retrieve data in ROR?
· How do I insert data into databases with ROR?
· What is tagging?
· What is Web 2.0?
· How can I make text editable without reloading the page?
· How can I use AJAX to make the page not have to reload to login?
· What is JRuby?
· How do I make elements draggable?

Tags: ,

Monday, March 06, 2006

Using AJAX and Ruby on Rails to Display Alexa graphs

I have posted a new tutorial on how to use AJAX and Ruby on Rails to display Alexa traffic graphs and site rank information at Designerz Blog.


eXTReMe Tracker