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

















An extremely nice blog you have here. I am keen your typing style and it’s very informative posts, I will go back here again!
Great tutorial, its really helpful, though I don’t use Ruby on Rails, but it would help me if I ever make up my mind to use Ruby on Rails in the future!
Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently quickly.
Super stuff! Thanks for the info
Thank you for any other great article. Where else may just anybody get that kind of information in such a perfect approach of writing? I’ve a presentation next week, and I’m at the look for such information.
As the knight of the quill never ventured into the fight, and only snuffed the battle afar, he knew nothing accurately of battles, but managed to pick up a few real or supposed incidents from the wounded and from stragglers.
Its such as you learn my thoughts! You appear to understand so much approximately this, like you wrote the ebook in it or something. I think that you can do with some p.c. to power the message home a little bit, however instead of that, this is fantastic blog. A great read. I’ll definitely be back.
A person essentially lend a hand to make seriously posts I’d state. That is the very first time I frequented your website page and up to now? I amazed with the analysis you made to make this particular publish extraordinary. Excellent job!
Thanks for any other informative website. The place else may just I get that type of information written in such an ideal method? I’ve a venture that I am just now working on, and I have been on the glance out for such information.
I beloved as much as you will receive performed right here. The cartoon is attractive, your authored material stylish. however, you command get got an nervousness over that you would like be turning in the following. in poor health no doubt come more before again as exactly the same just about a lot regularly inside case you shield this increase.
Terrific paintings! This is the type of information that are meant to be shared around the internet. Shame on Google for no longer positioning this post upper! Come on over and visit my site . Thank you =)
Wow, incredible weblog format! How lengthy have you ever been running a blog for? you make blogging glance easy. The whole look of your website is great, as well as the content!
It is the best time to make a few plans for the longer term and it’s time to be happy. I have read this put up and if I may just I wish to recommend you some fascinating things or advice. Perhaps you could write subsequent articles relating to this article. I want to learn even more things approximately it!
obviously like your website but you need to check the spelling on quite a few of your posts. Many of them are rife with spelling problems and I to find it very bothersome to inform the reality however I will definitely come back again.
I’m not certain where you’re getting your information, however good topic. I needs to spend some time learning much more or working out more. Thanks for fantastic info I used to be searching for this info for my mission.
I believe this is among the most vital information for me. And i’m happy reading your article. But should remark on few normal issues, The website style is great, the articles is truly excellent : D. Just right task, cheers
hello!,I love your writing very much! proportion we keep in touch more approximately your post on AOL? I require an expert in this house to unravel my problem. Maybe that’s you! Having a look forward to peer you.
It’s actually a nice and useful piece of information. I’m happy that you simply shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.
My brother suggested I might like this blog. He was once entirely right. This submit actually made my day. You can not believe simply how a lot time I had spent for this info! Thanks!
hey vaishnavi i am also a freelancer web developerand ia m getting work on ruby recently so i want to be in touch with me anand.sunny.7@gmail.com
You understand therefore considerably relating to this matter, produced me in my opinion consider it from a lot of various angles. Its like men and women aren’t interested until it’s one thing to do with Woman gaga! Your individual stuffs outstanding. At all times deal with it up!
really asweome post. thanks.
certainly like your web site however you have to test the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find it very bothersome to tell the reality then again I?ll certainly come again again.
You actually make it seem really easy with your presentation however I in finding this matter to be really one thing which I believe I would never understand. It sort of feels too complex and very vast for me. I’m having a look forward for your subsequent submit, I’ll attempt to get the grasp of it!
We’re a gaggle of volunteers and starting a brand new scheme in our community. Your website offered us with valuable information to work on. You have performed an impressive job and our entire neighborhood will be thankful to you.
In the new version 2, how would it be possible to replicate how we created custom pages in the previous versions of Magic Fields?
Hey Leute, dieses ist ein wie ich finde, toller blogg! Die Post’s sind stets echt unterhaltsam und interessant verfasst! Der jetztige Beitrag sticht aufjedenfall heraus ,deshalb habe ich diesen Blog als mein Favorit markiert,damit ich auch weiterhin so schöne Texte zu lesen bekommen.Wir lesen uns Mackenzie
I really enjoy reading your blog, because you have a very clear opinion of things and stand up to it, that we respect a lot. However, I am often astonished.
ohh…nice post but really?/?
This is really fascinating, You are an excessively professional blogger. I’ve joined your feed and stay up for in search of extra of your excellent post. Additionally, I’ve shared your site in my social networks
My brother recommended I might like this website. He was totally right. This post actually made my day. You cann’t consider simply how so much time I had spent for this info! Thank you!
You’re truly a just right webmaster. The web site loading pace is amazing. It seems that you are doing any distinctive trick. Furthermore, The contents are masterpiece. you have done a magnificent process on this topic!
You really make it appear so easy along with your presentation however I find this topic to be actually one thing that I think I would by no means understand. It kind of feels too complex and extremely vast for me. I’m having a look forward to your subsequent post, I will attempt to get the dangle of it!
Hi there, simply turned into alert to your weblog via Google, and located that it is really informative. I am going to watch out for brussels. I’ll be grateful for those who continue this in future. A lot of other folks will likely be benefited out of your writing. Cheers!
In the usual course of affairs I do not comment on articles but this is a very praiseworthy one, well done.
thanks for the useful post
Website Design Perth
An fascinating discussion is worth a comment. I feel that it is best to write extra on this subject, it may not be a taboo subject however generally individuals are not sufficient to speak on such topics. To the next. Cheers
Wow, marvelous weblog format! How lengthy have you ever been blogging for? you make running a blog look easy. The overall glance of your website is magnificent, let alone the content!
I would like to thank you for the job you have done when writing this article. I expect the same great quality from you later on too.
Hello my family member! I wish to say that this post is amazing, nice written and include almost all vital infos. I would like to look more posts like this.
Thanks for your list.This’s going to take short time to design for web.
Howdy very cool website!! Man .. Excellent .. Superb .. I will bookmark your website and take the feeds also?I am glad to search out numerous helpful info right here in the put up, we want develop extra techniques on this regard, thank you for sharing. . . . . .amberen side effects´s last 1
Someone essentially lend a hand to make critically articles I’d state. This is the very first time I frequented your web page and so far? I amazed with the research you made to make this actual submit amazing. Great activity!
naturally like your web site however you have to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I to find it very troublesome to tell the truth nevertheless I will certainly come back again.
Appreciate it for this post, I am a big fan of this site would like to keep updated.
At HypeConcepts, there’s no such thing as a common design job.
I was just seeking this information for a while. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative web sites in top of the list. Normally the top websites are full of garbage.
Great items from you, man. I’ve bear in mind your stuff previous to and you’re simply too magnificent. I really like what you have received here, really like what you are stating and the way wherein you say it. You are making it enjoyable and you continue to care for to keep it sensible. I can’t wait to read much more from you. This is actually a great web site.
Usually I don’t read post on blogs, however I wish to say that this write-up very forced me to try and do so! Your writing taste has been amazed me. Thank you, quite great post.
I am not certain where you’re getting your information, but great topic. I needs to spend some time studying more or understanding more. Thank you for excellent information I used to be on the lookout for this information for my mission.
whoah this weblog is great i really like reading your posts. Stay up the great paintings! You understand, a lot of individuals are hunting around for this information, you could aid them greatly.
It is surprising for many of us when you find fantastic guidance available on the web. sim card free mobile phones
I think other web site proprietors should take this site as an model, very clean and excellent user genial style and design, let alone the content. You’re an expert in this topic!
Nice post. I learn something on different blogs everyday. It is going to all the time be stimulating to read content from other writers and practice slightly something from their blog.
Only wanna input that you have a very nice web site , I like the design and style it really stands out.
My regards sir,This is my first time to visit this site and i have appreciated the your great work.Am still a student in third year and i will try some of these circuit to adverse in electronics.Am from Uganda and i would like to get a free software for testing building a circuit.Would you help me sir?Thank u
I simply couldn’t leave your website before suggesting that I extremely loved the usual information a person provide on your guests? Is gonna be back regularly in order to investigate cross-check new posts
Muslims think that Lord finally sent Muhammad (Seal from the Prophets) to share the actual divine message to the world (to summarize and also to finalize the term of Lord). In Islam, the “normative” demonstration of Muhammad’s existence is known as the actual Sunnah (literally “trodden path”). This instance is maintained inside traditions referred to as hadith (“reviews”), that recount his words, his / her actions, and the individual qualities. The classical Muslim jurist ash-Shafi’i (d. 820) pressured the need for the Sunnah in Islamic law, and Muslims are usually urged to emulate Muhammad’s actions within their everyday lives. The Sunnah is viewed as essential to guiding interpretation from the Qur’an. Six of the collections, put together within the 3rd century My oh my (ninth century CE), discovered be regarded as because especially authoritative through the biggest group inside Islam, the Sunnites. Another big group, the Shi?oh, features its own ?adith found in several canonical collections.
Nab5.com is an online marketplace where you can buy or sell a service for EURO 5 only.
They gained lots of popularity and is probably the best place to outsource any work.
nice informative stuff
i was looking for it thanks
website development company
There is a place that is close to my studio however I cannot discover any kind of testimonials on them. Do any of you know anything at all about them?
Nice tutorial, a few bugs but it worked great !
Hey Musikliebhaber. Es gibt eine klasse Internetseite bei der alle legal die besten Songs runterladen könnt! Ihr könnt direkt auf http://www.party-hits.org/packets/PartyMix_part1.rar gehen und euren Partysong downloaden. Finde ich schon super geil. Ist jetzt schon mein Geheimtipp für dieses Jahr !!!
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
In the event you’re however within the fence: grab your favored earphones, head down with a Finest Acquire and ask to plug them right into a Zune then an iPod and see which a single sounds better for you, and which interface helps make you smile much more. Then you definately’ll know which is proper available for you.
obviously like your web site but you need to test the spelling on several of your posts. Several of them are rife with spelling issues and I to find it very bothersome to tell the truth then again I will certainly come again again.
I’m no longer sure where you’re getting your info, but good topic. I must spend some time studying much more or figuring out more. Thanks for great information I was in search of this information for my mission.
Hi, i believe that i saw you visited my website thus i came to go back the choose?.I’m attempting to in finding issues to improve my web site!I guess its ok to use some of your concepts!!
Hi there, I discovered your web site via Google while searching for a related matter, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.
It’s perfect time to make a few plans for the future and it is time to be happy. I have learn this submit and if I may just I wish to recommend you few attention-grabbing things or advice. Perhaps you could write subsequent articles referring to this article. I desire to learn even more things about it!
Thank you for some other informative site. Where else may just I am getting that kind of info written in such a perfect way? I’ve a challenge that I’m simply now running on, and I’ve been on the glance out for such info.
I really like what you guys are up too. This sort of clever work and reporting! Keep up the superb works guys I’ve you guys to my own blogroll.
Hello There. I found your blog using msn. This is a really well written article. I’ll make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly comeback.
It is true that there are two main components to building a website: A domain name and web hostin. The guide even has some techniques which emphasie on how to bring traffice to ones websites. Good work
I enjoy what you guys tend to be up too. This sort of clever work and reporting! Keep up the terrific works guys I’ve included you guys to our blogroll.
Apple now has Rhapsody as an app, that is a fantastic start out, but it’s at the moment hampered because of the inability to retailer locally on your own iPod, and incorporates a dismal 64kbps bit rate. If this changes, then it will somewhat negate this advantage for your Zune, but the 10 songs every month will however be described as a huge plus in Zune Cross’ favor.
An impressive share, I simply given this onto a colleague who was doing a little bit similar analysis on this. He in fact purchased me breakfast because I discovered it for him.. smile.