July 10th, 2008
Tutorial : Developing your First Ruby on Rails 2 Application
So, you want to make an application using Ruby on Rails (RoR) huh ! Well, Lets try to make a simple “Article System”. Ruby on Rails is very easy at the same time a lil complicated. If you want to know more theory about Ruby on Rails, you can visit its official homepage http://www.rubyonrails.org. If you want a small summary of what it is, you can read my previous post Tutorial : Installing Ruby on Rails in Windows Vista/XP.
Like I said in my previous post, RoR uses the MVC Architecture. (M-Model, V-Views, C-Controller)
The below diagram must be self-explainatory, but if it is not, then
Models – Models communicate with the database, to retrieve the data and keep.
Controller – Any requests made by the browser are forwarded to the Controller by the View, which refers the Models and modifies it in different ways (methods written in the Controller) and returns the results to View.
View – This communicates with the browser, takes the inputs and forwards it to the Controller for the respective action, and the returned result from the Controller is forwarded by the view back to the browser.
Anyways, that was about MVC. So in RoR we always have to create these files for different functions.
For our Article System, our objective is to create a system in RoR
- Create Database ‘articlesystem_development’
- Take Article input from User
- Display All the Article
- Edit Article
- Delete Article
If we were to use PHP, this system would take not less than 50 Lines of Code, but in RoR …. you`ll soon find out;)
- Firstly open up Command Prompt (Start->Run) type cmd and click OK, then lets navigate to our ruby folder and create our application.
The Syntax to create a new application israils -d mysql appname
So type
C:\ruby\bin\>rails -d mysql articlesystem
A long list of files & directories are created.
- Before editing, Create a database articlesystem_development through phpmyAdmin. If you don`t know how to create a database then refer to Tutorial : Creating a Content Management System using PHP/MySQL else you can use the mysql command to create the database.
- Goto Start->Run. Type cmd and hit Enter. You will be prompted with the command prompt.
- type mysql -u username -p, hit enter
- It`ll prompt you for your password. Enter the password.
- Once your inside the console type CREATE DATABASE databasename \g i.e mysql>CREATE DATABASE databasename \g
- If you see the following then you have successfully created a database.
mysql> create database boo \g Query OK, 1 row affected (0.00 sec)
- Good ! Now navigate to F:\server\ruby\bin\articlesystem\config and open the file ‘database.yml’ in wordpad.
development: adapter: mysql encoding: utf8 database: databasename username: username password: password host: localhost test: adapter: mysql encoding: utf8 database: databasename username: username password: password host: localhost production: adapter: mysql encoding: utf8 database: databasename username: username password: password host: localhost
You will see the following,except the password area has not been edited yet so type in your mysql user password. (If you have followed the previous tutorial, then password is root), and please enter the same database name in all development,test and production.
- Save the file.
- Now comes the fun part. Open up Command Prompt. Now we need to create the tables for our database.
Our database schema isid(int) title(string) article(text)
1 test article bla bla bla.. lot of contentThe above post was just an example, so basically we have 3 attributes i.e id, title and article.
- We will be using rails “Scaffolding” feature to create these tables and link it with our system. Scaffolding as the name says, to clean the windows of a high rise building, scaffolding is used as support temporarily, similarly here we are going to use ‘scaffold’ to generate links & code.
- Now type in
c:\ruby\bin\articlesystem>ruby script/generate scaffold article title:string article:text
You`ll see notice that rails creates another bunch of files
C:\ruby\bin\articlesystem>ruby script/generate scaffold article title:string article:text exists app/models/ exists app/controllers/ exists app/helpers/ create app/views/articles exists app/views/layouts/ exists test/functional/ exists test/unit/ exists public/stylesheets/ create app/views/articles/index.html.erb create app/views/articles/show.html.erb create app/views/articles/new.html.erb create app/views/articles/edit.html.erb create app/views/layouts/articles.html.erb create public/stylesheets/scaffold.css create app/controllers/articles_controller.rb create test/functional/articles_controller_test.rb create app/helpers/articles_helper.rb route map.resources :articles dependency model exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/article.rb create test/unit/article_test.rb create test/fixtures/articles.yml create db/migrate create db/migrate/20080709183936_create_articles.rb C:\ruby\bin\articlesystem>
- I know, there are hell lot of files being created !!
Anyways, I`ll just tell you what RoR has generated, it has managed to create
- article.rb -> Model inside c:\ruby\bin\articlesystem\app\models\,
- articles_controller.rb -> Controller (Which has methods of all the functions i.e Create,delete,showall,edit) inside c:\ruby\bin\articlesystem\app\controllers
- index.html.erb, edit.html.erb, new.html.erb, show.html.erb -> View Files (More like templates which determine the looks of the site) inside C:\ruby\bin\articlesystem\app\views\articles
Remember MVC … you can check the code out. But don`t modify any right now.
- Now all you have to do is create the tables of the database. Hold on your horses, no need of logging in to mysql to create your tables. Just type this code
C:\ruby\bin\articlesystem>rake db:migrate
- rake db:migrate -> executes the database schema RoR had generated automatically,
Not only did RoR generate so many files, It also generated the table schema for articles.# This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20080709183936) do create_table "articles", :force => true do |t| t.string "title" t.text "article" t.datetime "created_at" t.datetime "updated_at" end end
- Voila !!! RoR has just created all the necessary tables for you in mysql. Don`t believe me ? go check your database. Don`t be amazed, thats nothing, now time to test our code, invoke the ruby web server
C:\ruby\bin\articlesystem>ruby script/server
- Point your web browser to http://localhost:3000/articles
- Congratulations !!! you have developed your first application in Ruby on Rails 2. Play around with the application, see what all you can do. RoR by default creates the delete,edit,create,show functions for your application when using “scaffold”. You can add articles, delete em, edit em or view all of em, from just 3 lines of code
This is the power of RoR !! Although I wrote a very basic tutorial (since I had less time), this tutorial covers a little theory of RoR’s architecture, how to create an application using rails in development mode, how to create a scaffold and finally to rebuild the database using rake db:migrate.
So I hope you had fun, you can modify the view files in C:\ruby\bin\articlesystem\app\views\articles if you want to change the look of it.
You can make the application start directly from http://localhost:3000/ I`ll be showing that, in my next tutorial for RoR which includes basic link routing, some more extra features to our article system. In the next tutorial I`ll also discuss about the singular & plural concepts in RoR which are very important. Till then Chow !















August 16, 2010 at 6:32 pm
I followed exactly the same procedure. but when i run http://localhost:3000/articles, then it giving me the error like this:
ActiveRecord::StatementInvalid in ArticlesController#index
Mysql::Error: Table 'articlesystem_development.articles' doesn't exist: SELECT * FROM
articlesRAILS_ROOT: E:/xampp/htdocs/articlesystem
Application Trace | Framework Trace | Full Trace
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract_adapter.rb:221:in log'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/mysql_adapter.rb:323:in
execute'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/mysql_adapter.rb:638:in select'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in
select_all_without_query_cache'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:60:in select_all'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:81:in
cache_sql'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:60:in select_all'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:664:in
find_by_sql'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1578:in find_every'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:618:in
find'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:638:in all'
E:/xampp/htdocs/articlesystem/app/controllers/articles_controller.rb:8:in
index'
July 31, 2010 at 9:04 pm
great work !!
But can you tell me how can I create one project outside ruby folder ie something like C:/rails -d mysql appname
I tried this but it does not work.Can you please throw some light on this.
Regards
Noddy
August 3, 2010 at 6:54 am
Hi Noddy,
Most probably, you haven`t added the path of your "X:rubybin -> Your ruby installation folder" in Control Panel -> System – Environmental Variables -> Path.
Once you have done that, restart the system, then try the above.
Regards
July 2, 2010 at 6:20 pm
Hi guys I'm on the early stages on learning Ruby.
The thing is that I really don't have an idea on how to use an existing database filled with tables and data on ruby. Every guide, every article that I have or find on the internet is always creating a new one using the migration functions.
But which are the steps for using an existing tables on RoR?
Thanks in advance.
January 16, 2010 at 10:38 am
I got solution. Basically i have typed my password just after colon without leaving any space in database.yml
Sorry for silly question and thanks a lot for this complete guide
January 16, 2010 at 9:58 am
I followed exactly same procedure as you told me but when i used
c:rubybinarticlesystem>ruby script/generate scaffold article title:string article:text
It showed me an error "C:/Ruby/lib/ruby/1.8/yaml.rb:133:in `load': syntax error on line 24, col 2: ` host: localhost' (ArgumentError)"
Please guide me through
December 5, 2009 at 12:50 pm
This article clarified many Ruby on Rails mysteries. I find it very useful. Thanks for writing and publishing it!
July 9, 2009 at 6:14 pm
Thanks for the tutorial i have 2 questions
How do you custimise the page? (e.g. the page where yoou view the news article).
Is ROR better then PHP?
June 9, 2009 at 1:11 am
“Help+Dumbness=? (required)”
Where could i get a demo of this?
_____________________________________________
“Meaning of life-Mew=? (required)”
June 9, 2009 at 9:34 pm
Actually Dave, there is no demo of this particular tutorial since it is very simple. If you have any problems you can always ask
July 17, 2009 at 8:25 pm
It would be allot of help if you can upload the files for a demo?
I think HostGator (VisionMasterDesigns Web host) will support Ruby on rails
June 5, 2009 at 11:09 am
Replacing the libmySQL.dll from a MySQL 5.1 installation with one from a 5.0 version, downloaded directly from http://www.mysql.com worked perfectly. I can’t believe it! sooooo many hiccups trying to get rails running well on an XP machine. Looks like progress! thanks…
April 3, 2009 at 12:38 am
Jaime, that really worked, I was having the same
problem.
Thanks,
March 26, 2009 at 4:11 am
Hi All,
I was having the same problem and the following post help me to fix it. http://forums.aptana.com/viewtopic.php?f=20&t=8271#p30240
I think the problem is the libmysql.dll client library version, I mean, if you have libmysql.dll in your path or you copied to \bin from directory, you ended up with a libmysql.dll client 5.1.X You can fix the problem without installing a new server by replacing libmysql.dll client 5.0.X. I got mine from php installation.
I hope this helps,
Saludos,
Jaime
January 22, 2009 at 4:45 am
@David
Hi all,
I have exactly the same problem – although I’ve exactly these versions: MYSQL 5.0.67 and mysql-gemdriver version 2.7.3.
>rake db:migrate –trace
(in C:/ruby/projects/CM)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
== CreatePeople: migrating ===================================================
– create_table(:people)
-> 0.1100s
== CreatePeople: migrated (0.1100s) ==========================================
** Invoke db:schema:dump (first_time)
** Invoke environment
** Execute db:schema:dump
rake aborted!
Mysql::Error: Commands out of sync; you can’t run this command now: SHOW TABLES
When doing ANY KIND OF DATABASE ops, the Mongrel- and WebBrick-Servers crash with Segmentation Faults. I’ve already googled for days, but still no idea for a solution.
PLEASE HELP..
Ciao,
Arno
January 20, 2009 at 2:04 pm
@Luis Jaramillo
Hi Luis,
I didn’t make anything extra. I just changed MYSQL from 5.1 to 5.0.67 and It worked. Mysql gem driver version was 2.7.3. In my case, I didn´t have any previous application running, I mean, the problem didn’t appear after an updating of my application. I just tested a “hello world” RoR application. The easiest way. I say this because you could have your app running with several tables in your database and the version change could be not so easy. If you already have your 5.1 database running with content, try to test 5.0.67 database separately.
Saludos,
David
January 20, 2009 at 10:18 am
@David
Hi David,
I have the same problem, David are you sure the solution is to change the version of MYSQL? or by making something extra.
Please confirm me to make changes and solve this problem.
thanks.
Luis Jaramillo
December 31, 2008 at 5:45 am
Hi,
I got the same problem everytime I run db:migrate command. The solution that I’ve found is to change my mysql server. I was using 5.1 version and now I’m using 5.0.67.
note: I use 2.7.3 mysql gem driver
Bye and happy new year!!
David
December 25, 2008 at 5:46 pm
@jab
Hi Jab,
I run into the same problem. Have you find a solution for this issue yet?
December 4, 2008 at 11:25 am
hi
during db:migrate , there was an error occured. it said
Mysql::Error: Commands out of sync; you can’t run this command now: SHOW TABLES
but then the tables were created succesfully. and my articlesystem went up just fine.but then when i tried creating a new article.then i cliked create.and i get this error
ArgumentError in ArticlesController#show
NULL pointer give
app/controllers/articles_controller.rb:16:in `show’
what could hav been the problem.pls help.
October 2, 2008 at 6:57 pm
you can create the database without typing the following command
mysql>CREATE DATABASE databasename \g
simply editing the file database.yml and running the command
rake db:create:all
Rails 2.0 will create three databases development, test and production
September 11, 2008 at 11:29 am
finally, an updated tutorial. thanks! keep it coming. =)
August 28, 2008 at 6:02 pm
Found the problem.
I installed ruby on xampp and it didnt like it.
Solution was to unistall ruby then reinstall ruby and recreate the site outside of the xampp folder.
Added the following to httpd.conf:
Listen 3000
LoadModule rewrite_module modules/mod_rewrite.so
#################################
# RUBY SETUP
#################################
ServerName rails
DocumentRoot “c:/ruby/bin/articlesystem/public”
Options ExecCGI FollowSymLinks
AllowOverride all
Allow from all
Order allow,deny
AddHandler cgi-script .cgi
AddHandler fastcgi-script .fcgi
#################################
# RUBY SETUP
#################################
August 28, 2008 at 5:04 pm
Looks like a good tutorial but I get the following error when performing the “ruby script/server” command, any ideas?
C:\ruby\bin\articles>ruby script/server
=> Booting WEBrick…
=> Rails 2.1.0 application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with –help for options
[2008-08-28 12:29:21] INFO WEBrick 1.3.1
[2008-08-28 12:29:21] INFO ruby 1.8.6 (2007-09-24) [i386-mswin32]
[2008-08-28 12:29:21] WARN TCPServer Error: Only one usage of each socket address (protocol/network address/port) is normally permitted. – bind(2)
C:/ruby/lib/ruby/1.8/webrick/utils.rb:73:in `initialize’: Only one usage of each socket address (protocol/network address/port) is normally permitted. – bind(2)
(Errno::EADDRINUSE)
from C:/ruby/lib/ruby/1.8/webrick/utils.rb:73:in `new’
from C:/ruby/lib/ruby/1.8/webrick/utils.rb:73:in `create_listeners’
from C:/ruby/lib/ruby/1.8/webrick/utils.rb:70:in `each’
from C:/ruby/lib/ruby/1.8/webrick/utils.rb:70:in `create_listeners’
from C:/ruby/lib/ruby/1.8/webrick/server.rb:75:in `listen’
from C:/ruby/lib/ruby/1.8/webrick/server.rb:63:in `initialize’
from C:/ruby/lib/ruby/1.8/webrick/httpserver.rb:24:in `initialize’
from C:/ruby/lib/ruby/gems/1.8/gems/rails-2.1.0/lib/webrick_server.rb:58:in `new’
… 7 levels…
from C:/ruby/lib/ruby/gems/1.8/gems/rails-2.1.0/lib/commands/server.rb:39
from C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require’
from C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require’
from script/server:3
When I try to visit http://localhost:3000/articles I get a 404 error…..
?
July 31, 2008 at 5:21 am
Awesome! I have only just started looking into developing using Rails (Im a PHPer) and the development speed is very impressive!
July 21, 2008 at 8:54 pm
July 21, 2008 at 8:30 pm
perfect works great.
thanks!
July 21, 2008 at 6:27 pm
Hey Tyler,
Sorry for the delay in replying, do one thing,
The is the database must exist prior to raking. then using rake db:migrate automatically creates the tables.
You can follow this method as well
create a application simply
“rails appname”
then edit the “database.yml” folder inside your app/config
replace the code with the following code.
development:
host: localhost
adapter: mysql
database: put the database you want to use
username: put your db username
password: put your db pass
After this, see to it that the database exists in mysql either you
then follow with creating a scaffold and then raking it. It should work fine now.
I`ll add it to the tutorial as well. Thanks
Regards
July 21, 2008 at 1:25 pm
Hi, I get an error #42000 when i rake db:migrate, unknown database “articlesystem_developemnt” I can manually add the database, but is there another way around that? thanks, great tutorials by the way.
tyler
July 13, 2009 at 2:31 am
when i rake db:migrate, unknown database “articlesystem_development” I can manually add the database….
Same problem here!
rest of the tutorial works perfect