Tutorial : Creating your first application in Rails 2.3.3 using MySQL (Ruby on Rails)
Learn to create a an application in Ruby on Rails 2.3.3 (first application for the newbies)
Rails is an amazing framework for Web Development. Most of us don`t really know how fast and easily you can create applications using Ruby on Rails. Rails applications has always had trouble with deployment (methods of deployment have improved with the latest versions) but nonetheless, the power of application development using Rails in least amount of time is something still other web frameworks cannot provide.
About this Article
Having said, this simple tutorial will not only teach you how to create your first application in Rails, but also information on how primitive generators are used in rails.
I am Assuming you have heard of Ruby on Rails and Model – View – Controller Architecture.
What are we building ?
A Simple application to add/edit/delete and view User Information. (Imagine it to be an Employee managing application). Our Primary goal is to create an application which will display all User info stored in the databse. It should allow us to
- Create a New User
- Edit an Existing User
- Delete an Exisitng User
- View All Users
There are many tutorials out there which explain how to create Rails applications, this article is intended for the newbies interested to know more about Ruby on Rails.
Index
- Create Rails App
- Configure Rails App to work with MySQL
- Confirm connection with MySQL
- Start Coding
- Run Application
- Add Validation to forms (to make it look prettier
) - Conclusion
Requirements
Please note that, Rails 2.3.3 works best with Ruby 1.8.6 rather then Ruby 1.8.7 in a Windows powered local machine.
A system capable of running Ruby on Rails applications for development and testing purposes.
-
Create Rails App
Open up “Command Prompt” (Start->Run (type in CMD ↵)). You can directly jump into creating your first Rails app by typing one of the following (remember we are creating a Rails app preconfigured to work with a MySQL Database)
C:\myrailsapplications>
rails myapp -d mysql↵
OR
C:\myrailsapplications>rails --database=mysql myapp↵
Rails Application Structure
Rails will create a host of directories with a similar structure as shown in the image.
Now, if you want to create a MySQL based Rails application, use the above code to create one. Rails will create all the directories and configure your application to work with a MySQL Database instead of its default SQLite.
-
Configure your Rails app to work with MySQL
Ok, we have created a Rails application to work with MySQL, but you need to specify the most important part for any application to connect to MySQL viz username, password.
Navigate to
myapp/configand opendatabase.yml. We need to fill in theusernameandpasswordfor our MySQL Connection.Remember every Rails application can be run in any of the following 3 modes. Every mode has various pros and cons. We will be concentrating with the “development” mode.
- development
- production
- test
This is how your
database.ymlshould look like, with filled in values forusernameandpassword.development: adapter: mysql encoding: utf8 reconnect: false database: myapp_development #will use this database for dev pool: 5 username: root #my mysql username password: root #my mysql password host: localhost test: adapter: mysql encoding: utf8 reconnect: false database: myapp_test pool: 5 username: root #my mysql username password: root #my mysql password host: localhost production: adapter: mysql encoding: utf8 reconnect: false database: myapp_production pool: 5 username: root #my mysql username password: root #my mysql password host: localhost
-
Lets check the connection with MySQL.
You know what the best part is…you have an option of either letting Rails do all the database manipulations directly, or you can use PHPMyAdmin or any other 3rd party tool. Rails is here to help us, from creating a database from scratch to modifyin it and till destroying it.
Guess what, all of these actions are versioned (Rails likes to call this “migration”), so you can always go forth and back between various versions of your actions on manipulating the database
Rails provides a Rake task that can take care of creating the database. Type the following commands to create teh databases directly via Rails.
-
C:\myrailsapplications\myapp> rake db:create RAILS_ENV='development'
Yes Creates the database specified in the “development” section of database.yml
-
C:\myrailsapplications\myapp> rake db:migrate
This is one of the most important commands in Rails. It is used everytime when you want to manipulate the database in any way. You`ll be seeing this command frequently being called everytime we have to manipulate teh database.
Now its time to check whether our magic code worked or not. Either you’ll get the command prompt back (success) or you’ll get an error of some sort. The error means that Rails can’t currently work with your database. If you do see an error, It’s probably a simple configuration issue.
-
-
Lets start developing our User Managment Application
What are we doing ?
Our Primary goal is to create an application which will display all User info stored in the databse. It should allow us to- Create a New User
- Edit an Existing User
- Delete an Exisitng User
- View All Users
So we would require a table called “user” with attributes “firstname, lastname and salary”, to fetch the results from.
Database Schema :

User("id","firstname:string","lastname:string","salary:decimal")
On an average, this application if done via PHP would take atleast anywhere between 0.5hours-1.5hrs (by a pro) and atleast 100-200 lines of code. Lets see what Rails has to offer.
Start Coding :
- We`ll be using an unique generator in Rails to achieve this called Scaffold. This generator, automatically creates a model, controller and views of a particular object (in our case User)
The Syntax to use a Saffold is
C:\application directory>ruby script/generate scaffold A B
A : Scaffold name (in our case “user”)
B : what all attributes you want for this scaffold (What attributes do we need to store about a “user” viz “firstname,lastname and salary”Now that you know the syntax, lets run the code in the command prompt.Note : that on the command line that follows, we use the
singular form,Userinstead ofUsers.In Rails, a model is automatically mapped to a database name mapping table whose name is the plural form of the model’s class. In our case, the model is called
User, so Rails associated it with the table calledusers.C:\myrailsapplications\myapp> ruby script/generate scaffold user fname:string lname:string salary:decimal
- You`ll notice a series of files being created after executing the above code. The one we’re interested in first is
the migration20090805075034_create_users.rb. The migration has a UTC based timestamp prefix (20090805075034), a name (create_users), and a file extension (.rb, because it’s a Ruby program).Since we already specified the columns we wanted to add on the command line, we don’t need to modify this file. All we need to do is to get Rails to apply this migration to our development database. We do this using therakecommand.C:\myrailsapplications\myapp> rake db:migrate
-
Run the Application
Wondering why run the application without typing “actual” codes ? We must have typed barely 4 lines of code. Well thats the beauty of Rails.
C:\myrailsapplications\myapp> ruby script/server
Now navigate your browser to http://localhost:3000/, You will see a page similar to the image in the left. You must be wondering what page is this ??
Well this is Rails Welcome page, when you click on “About your Application’s Environment”, all the respective variables will be shown if your Rails application is successfully connected to the database else you will get an error.
To see our application in action, navigate your browser to http://localhost:3000/users (since our scaffold was “user”)
-
Add Form Validation
Navigate to “
myapp/apps/models/” and open user.rb. Replace the code inside withclass User < ActiveRecord::Base #checks for the presence of some text in firstname,lastname validates_presence_of :firstname, :lastname validates_numericality_of :min_salary #call our function - min_salary validate :min_salary #function defination where salary is checked for its presence and minimum value def min_salary errors.add(:salary, 'should be at least 0.01' ) if salary.nil? || salary < 0.01 end end
Some Predefined Validation Checks
validates_presence_of– Validates the presence of any character in that textfield
validates_numericality_of– Validates the presence of any numerals in that textfield
validates_uniqueness_of– Validates the uniqueness of that field (checks the database for the same name)
-
Conclusion
I hope this tutorial is useful to all beginners learning Ruby on Rails. Rails 2.3.3 has introduced a lot of new features, and I`ll be covering as we go. If you guys have any questions, lemme know


















Not very helpful to new users. Full of bugs
thanks michael, it helped a lot
in users.rb
validates_numericality_of :min_salary
should be
validates_numericality_of :salary
Whats with this – where is the fix please techsearch@me.com
NoMethodError in Users#index
Showing app/views/layouts/users.html.erb where line #12 raised:
undefined method `^' for "2":String
Extracted source (around line #12):
9: </head>
10: <body>
11:
12: <p style="color: green"><%= flash[:notice] %>
13:
14: <%= yield %>
15:
Hi there
A very easy and straight forward tutorial, thank you.
Unfortunately I get the following error when I try to input some valid data:
NoMethodError (undefined method 'min_salary_before_type_cast' for #<User:0xb72851ec>)
app/controller/users_controller.rb:46:in 'create'
…
Not sure what I have missed, can anyone advise?
In Versions above Rails 2.0 , the scaffold does not generate the views from the model . It creates only blank pages.
We need to manually add text fields, textbox etc to it. In windows it often says libmysql.dll not found. You need to copy download http://www.dll-files.com/dllindex/dll-files.shtml... and copy it to C:/Ruby/bin folder in order to solve this error.
Happy Rails Coding
Regards
Saurabh
hi,
I am trying to learn ruby and rails and no matter what i do nothing works like it should(seems to be allot of probs with the mysql+RoR working together….not sure.Thanks for the tutorial although it isn't working at all for me either ;(.Any tipps for someone brand new to this all?I continually get the mesage in the shell (developement database not configured) i have it set right in the .yml and also set up on mysql….)
oh,your DEMO link doesn't seem to work either.
Excellent tutorial, Michael, but I’ve a question. How can I make a scaffold
inside a subdirectory? For example, I’m trying into
localhost:3000/admin/publisher
How can I make that?
I was trying with script/generate scaffold ‘admin/publisher’ name:string,
but it didn’t work.
Can you help me?
Thanks in advance!
Hey Christian,
you can create a subdirectory just like the one you are doing
ruby script/generate scaffold admin/product title:string(skip the single quotes'')Regards