Ruby On Rails with MySQL "Rails Hello World" | ![]() |
![]() |
Written by Arash Karimzadeh |
Thursday, 09 April 2009 07:14 |
If you do not have installed the RoR (Ruby on Rails) yet, read this article. Here we will create our first "hello world" application and gradually extend it to communicate with database. Lets create our first project using MySQL configurationOpen the command prompt and find the destination you want to create your project. If you dont know how to use command prompt check . For example I want to create my project in drive D; so I use the following command. rails --database mysql firstApp --database mysql will tell the rails to generate proper db configuration in my \config\database.yml. Check this file and set development information with correct values. Also remember to create a schema named firstApp_development in your MySQL. Lets start our webserver We can start it by using following command in out project directory: ruby script/server Now you can check your application at this address http://localhost:3000. You will see the rails welcome page. Lets create our hello world pageAs you know RoR is MVC(Model-View-Controller) framework. So what we need is to create a helloworld controller. Lets open another command prompt and use rails generator to create our files: ruby script/generate controller say helloworld It will create some files and folders. As you see the files name will contain 'say' and if you check the app\controllers\say_controller.rb there will be helloworld method. Change it to:
Also edit the view file which is app\views\say\helloworld.html.erb to:
Now lets checkit at http://localhost:3000/say/helloworld. If you see an error you must stop your web server by pressing CTRL+C key in your command prompt and re run the ruby script/server command. Lets create more dynamic greetingsRun this command at the root of your project (mine is D:\firstApp\) ruby script/generate scaffold greeting message:string This command will generate model, view and controller for our greeting with a message field which is string. There is one important file which is created at db\migrat\20090328143658_create_greetings.rb.This is the file which will generate our table in firstApp_development schema. by following command: rake db:migrate *Remember: If you didn't set \config\database.yml properties correctl, it will fail. Lets restart our web server and check it at http://localhost:3000/greetings. As you see now you have CRUD by one command. I insert a new message "hello dynamic world!". and return to my greetings list page. Now lets change our SayController to always show the last message in greetings as our greeting.
and check the http://localhost:3000/say/helloworld. More updated version of this article is available at www.elemenex.com |
Last Updated on Friday, 24 April 2009 05:27 |