Beginners Guide to Rails, part 1

36 comments | Posted: 31 March 06 in Tutorials, by Robert Evans

Introduction

The last write up I did here focused on the simplicity and flexibility of the Rails framework when using databases. This article will begin a series of tutorials that I will be writing here and cross posting on my site. My hope is that I can guide those who are very new to Rails and Ruby on the path of learning this awesome framework and language.

WARNING: This tutorial is not for those who are already building applications using the Rails framework. This is geared towards those who have not yet used Rails to build an application or a web site. Also, this article assumes that you do have some knowledge of setting up MySQL databases through an administrative program (via command line or another program).

For those curious, I use the following for my Ruby on Rails developing:

Ok, let’s start Building!

First thing we need to do is create a database. Open up MySQL Administrator and create three databases. Name them:

The first thing you should notice is the naming convention used here, particularly development, test and production. Development is for our development phase. When we make code changes to our application, we can see the changes instantly (browser refresh). The test is for doing Unit Testing, which should always be done before production. Lastly, production is when we have finished our application and are ready to let the world see it. If you make changes to the code while in production mode, you will not see the changes happen instantly.

So, we have created our three databases, now it is time to create our Rails application. Open up the command line and navigate to where you want your application to reside. Once there, type the following command:

rails Contact

This creates the framework of our application. The files that you will spend most of your time in are the app, db, and public. Later when you are building more sophisticated applications you will be using the other files that Rails creates for you.

The Database Glue

To connect your new Rails application to your existing database you now need to open up the database.yml file. You will find this file inside the config folder in your Rails application. Since we are using MySQL as our database, then you will configure only the MySQL part, not the PostgreSQL or SQLite. MySQL configuration will be found at the top of the database.yml file.

Look for the following code:

development:
  adapter: mysql
  database: contact_development
  username: root
  password:
  socket: /path/to/your/mysql.sock

That will be the default for the development (contact_development) database. If you have a password for your databases add it to the password field above. Do the same for your test and production configurations. Your socket path most likely will be /tmp/mysql.sock if you are on a windows machine.

Let’s Migrate!

As you recall, we created our database, but we haven’t created any tables yet. We could create the tables in our MySQL Admin program, but that wouldn’t be very Rails-y, would it? So, we are going to create a migration file and write our tables in Ruby. First, make sure you are in the contact directory in the command line and then I want you to type the following:

ruby script/generate migration contact_db

You will see a folder named db/migrate was created and a file called 001_contact_db.rb. The 001 is your migration version number. I am not yet going to explain all the nuances of migrations. My point for this first article is just to walk you through creating your first application. Basically, migrations make database upgrades and changes very easy. It allows you to evolve your database schema as your application’s code evolves.

Now, I want you to open the 001_contact_db.rb file (ruby/contact/db/001_contact_db.rb) in your editor of choice. We are going to be writing in our table. Go on, I’ll wait. Ok, good. I want you to add the following to your contact migration file in-between the def self.up and its corresponding end.

create_table "people" do |t|
  t.column "id", :integer
  t.column "name", :string
  t.column "address", :string
  t.column "city", :string
  t.column "state", :string
  t.column "zipcode", :string
end

When you are done, your file should look like this:

class ContactDb < ActiveRecord::Migration
 def self.up
  create_table "people" do |t|
   t.column "id", :integer
   t.column "name", :string
   t.column "address", :string
   t.column "city", :string
   t.column "state", :string
   t.column "zipcode", :string
  end
 end

 def self.down
  drop_table :people
 end
end

Notice that in the def self.down there is drop_table :people. This is in case you want to drop that table if you version down your database.

First, create_table “people” do |t| creates the table people. Then, t.column is your table column. The quoted text following t.column is your field name. The next piece following the table name is your declaration of what type of field it is. :string is the same as varchar(255).

Now, we are going to execute this migration file. Go back to your command line and type the following to execute the migration file:

rake migrate

Now, your contact database has your table people. Go take a look. You will see your people table and a schema_info table. What is the schema_info table for you ask? It holds your database schema version number.

Behold, Scaffolding

We are going to do a quick and dirty method to building the framework of our new application. Go to your command line, and in your contact folder type the following command:

ruby script/generate scaffold Person

What this does is creates our model, controller and view files for us. It also adds pre-built code to our controller and view files. With this, we can now enter data into our database via our application. Want to see? While still in your command line, type the following to start up the WebBrick server:

ruby script/server

In your browser, browse to localhost:3000. You should see a Welcome aboard sign with the rails logo. If you do, congratulations, the server is running! Now, let’s go to our application. In your browser, browse to localhost:3000/people. Wait…didn’t we just create our scaffold called person? Yes, we did. If you read my last article here on Godbit, you will know that rails prefers its database names to be plural, hence the name people. In our rails application, we create our model and controller to be singular, hence person. You can always override this if you wanted to, but for now, we are just going to go with the flow.

So, you should see your application up and running now. Go ahead and click on new person to create a new person to enter into your database. Once you enter the information and click create, you will see that rails has populated your database and now displays it for you to see.

What just happened?

Well, the Scaffolding generator creates the skeleton code for us. It creates the code necessary in the controller and view files. Go ahead now and take a look in the app/controllers folder and the app/views folder. In the controllers folder you will see a file called people_controller.rb. That file was created by our Scaffolding call earlier. Open that file up in your favorite text editor.

You will notice that there are various def calls inside. Def is your definition method that defines, well your methods. Notice the first one, index. This corresponds to index.rhtml. Wait, there is no index.rhtml file. If you are familiar with creating web sites, you will know that if you go to say bioevans.com, the server looks for index file to display. The extension can be html, php, asp, etc. Same thing applies to rails applications. Well, we don’t have an index file, but localhost:3000/people displays just fine. So, what is going?

In the method index, (back to the controller file) you will see a call, called, render :action => ‘list’. What this means is that the list action is being rendered. Look for the method called list. That method is being called by the index method. Basically, render means what we are going to render, :action means what action is going to take place, and that action points to list.

One thing you should you know, is that the methods list, show, edit, and new also have views with the same name. If you don’t insert a redirect (we’ll talk later about it) or render into your methods, inside the controller, then rails will look for a view file that has the same name as the method. All rails html files have the extension rhtml allow you to embed Ruby code. Pretty cool, huh?

Conclusion

We haven’t even touched the tip of the ice burg yet and have only look at a few basic concepts. In the next article, we are going to edit the scaffolding code, talk about what those other functions in our controller are doing and learn how CSS and Rails play nicely.

In upcoming articles, we will continue to build our contact application with a complete backend system, search capabilities, sorting, Ajax implementation, Routing, uploading to your server, and various other things that I may add along the way. Till then, God be with you!

Read Part 2

Discuss This Topic

  1. 1 Yannick

    Another good one Robert (well at least for me being new to RoR). Thanks. I look forward to the next in the series.

    A quick question though, lets say I chose to create the table from within MySQL instead of coding it in ruby, would I still be able to have the ability to “version down” if I needed to?

     
  2. 2 Robert

    If you already had an application with a database full of tables, you can always convert it over to a migration. You do so by opening the command line and moving to your rails application directory and typing the following: rake db_schema_dump. You will see in your db file in the rails app directory a file named schema.rb. Then create your new migration file by typing in the command line ruby script/generate migration your_schema. Cut and paste the data from the schema.rb file into your new 001_your_schema.rb file. You will need to add the following piece of code to each of your create_table lines: :force => true. Your create_table lines should look like the following: create_table “table_name”, :force => true do |t|. This will force the new migration to take place within your db.

    Now, you just run your rake migrate command from the command line and your db will be updated. If you wanted to move to a different version, say you have 4 versions currently, you just type rake migrate VERSION=3 to move to version 3.

    Oh, and when you are cutting pasting your db code, just the code inside the class, not the ActiveRecord::Schema.define part.

     
  3. 3 Robert

    I forgot to mention that if you prefered to not use Rails migration at all and wanted to version down, you would have to do so within MySQL itself and make the appropriate changes to your Rails code(forms, outputs, etc)

     
  4. 4 Yannick

    Thanks Robert. In the past I would normally create the tables in MySQL instead of using Rails migration. At least I know how to convert it now.

     
  5. 5 Casey

    I submitted this article to digg earlier. Thanks for a great tutorial!

    Article on Digg

     
  6. 6 Yannick

    Nice, it made it in the front page too.

     
  7. 7 EN05

    Well written,,,,been waiting for someone to do this for a while..
    Thanks

     
  8. 8 Dietrich Murphy

    How do you open the command line? How do you navigate? I am using Windows XP.

     
  9. 9 tomasz

    @ Dietrich Murphy

    Start > Run > “cmd” to open the command line (or ‘shell’)

    once its open you can navigate by using the ‘cd’ command,

     
  10. 10 Tobi

    To open the command line, select “Run” from the Start Menu und type in “cmd”. Afterwards, a black window should open on the screen.

    Navigation is quite straightforward: to move to a directory you type in “cd XXX” (cd = changedir), where “XXX” stands for the directory you want to move (e.g. “windows”). To leave a directory, you simply type in “cd ..”. To view all the files and sub-directories of the directory, you are currently in, type in “dir /p”.

    I hope, this comment was helpful!

     
  11. 11 seventoes

    If you dont know how to open the command line and how to navigate in it, you shouldnt have a web server…

     
  12. 12 Robert

    Thanks for the digg Casey! I am surprised it made it to the front page.

     
  13. 13 Kyle Heon

    Looking forward to more installments. I’ve had the Pickaxe book and the Agile Rails book since it was in beta but just haven’t been able to spend the time I want learning Ruby/Rails. I can’t wait till I reach that Eureka! moment though.

    I’m especially interested in learning more about how the Migrations system works. It certainly changes the way I’d design a database but in the end it’s for the better because you can easily push changes around.

    Thanks.

     
  14. 14 Joey Guerra

    Nice article, but the main problem I have with Rails is getting it up and running with Apache/FastCGI. Using WeBrick, for me, is just not practical. When my app is deployed, it’s on Apache or IIS. So, developing in WeBrick doesn’t help me.

     
  15. 15 Hagrin

    Great tutorial. I’ll definitely be reading through it again when I get a chance later this weekend.

     
  16. 16 Stuart

    Good beginner article. One thing I would like to see in this series is a good tutorial on unit testing. I’m just now trying to get a grip on the test framework.

     
  17. 17 Paul H

    Robert, a big thanks for putting this together. I plan to be playing with this on the weekend, but it already makes a large chunk of sense just from reading. This looks like a great start for me, thanks for keeping it simple.

    I have a question (which I am sure I will figure out myself fairly soon) which does rather highlight my non-developer graphic/multimedia background: Why the three databases, is this a good design practise, or does this reflect how RoR likes to be set up?

    Thanks again! Paul

     
  18. 18 Robert

    Paul: The three database setup is 1. good design practice because 2. You will be developing your application and using a database (the development) that has sample data and 3. when you have completed your application you are going to want to test it doing Unit Testing (and using the test database). Then 4. when you are production ready you will be using the production database.

    Going by these methods, it won’t matter if you are coding at home on your own machine, on your server machine or at work on work’s server machine. If at home, you will most likely be uploading your project to a server, but if you are developing on a server or at work using their server, the project will most likely be where it is going to be.(maybe a few folder changes, but the database remains). Basically, it is best practices.

     
  19. 19 Mark Priestap

    I can’t wait to dig into this. Thanks so much Robert! I’m working with a Rails developer right now, so this will be really helpful.

     
  20. 20 Lisa

    This is a great tutorial—but I’m having a problem.
    I’m trying to detach an old project from port 3000 but “ruby -d” isn’t working. Do you have ANY idea how to do this? I’ve been searching online for hours!

    Thank you!!!

     
  21. 21 Robert

    You’re welcome Mark!

    Lisa, I have a couple of questions:

    1. Are you running WebBrick?
    2. Have you stopped WebBrick and restarted it in your new project folder?

    It sounds like to me that you have the WebBrick server running for your old project, which means you need to stop the WebBrick server, move to your new project file and start it again in the new project folder.

     
  22. 22 Lisa

    Oh Robert—thank you!

     
  23. 23 Robert

    You’re welcome Lisa!

     
  24. 24 adk

    when i get to the “rake migrate” part i get this error.

    (in /home/adam/rails/Contact)
    rake aborted!
    Packets out of order: 13: SELECT version FROM schema_info
    ./Rakefile:200

    have i done something wrong?

     
  25. 25 Robert

    Was your file created? It sounds like a user permission problem, but there isn’t much to go off of here.

     
  26. 26 adk

    well, I’m not sure what was going on. i had installed mysql manually. and i was using an older ruby and rails from the kubuntu repositories. so installed XAMPP (which is great btw), Ruby 1.8.4 and Rails 1.1.2 and everything works fine now. Great article. Thanks.

     
  27. 27 Jamie Fehr

    I didn’t check to far down the comments, but I think one thing worth noting here is that you do not need to specify an “id” column in your migration, rails adds it automatically, also in Rails 1.1 a migration is created every time you generate a model.

     
  28. 28 Ernie Oporto

    Good article. Looking forward to the next ones!

     
  29. 29 Richard White

    Might want to mention Ajax Scaffolds as an alternative to regular rails scaffolds… http://www.ajaxscaffold.com

     
  30. 30 Robert

    Hi Richard. When I start talking about Ajax, I will cover your Ajax scaffolding briefly as well. Nice job on that btw!

     
  31. 31 Sri

    Everything went on well until I typed ‘rake migrate’. I get the following:

    /home/sridkat2/public_html/testapp/public/Contact/db/migrate$ rake migrate
    (in /home/sridkat2/public_html/testapp/public/Contact)
    rake aborted!
    getaddrinfo: Name or service not known
    (See full trace by running task with—trace)

    BTW, I don’t see the line “socket: /path/to/your/mysql.sock” or for that matter even the word ‘socket’ in my database.yml.

     
  32. 32 Robert

    Sri, go to /home/sridkat2/public_html/testapp/public/Contact and type rake migrate.

    If you don’t have the socket, from Rails 1.0, then don’t worry about it.

     
  33. 33 Sri

    Did that and still get the same:

    /home/sridkat2/public_html/testapp/public/Contact$ rake migrate
    (in /home/sridkat2/public_html/testapp/public/Contact)
    rake aborted!
    getaddrinfo: Name or service not known
    (See full trace by running task with—trace)

     
  34. 34 Robert

    Did you create your migrate file and add the table information into it? If so what does the trace say after run the rake migrate command?

     
  35. 35 Sri

    Yes, I did.

    If it matters, the names of the DBs get prepended by my cPanel account name like so: sridkat2_contactdevelopment, sridkat2_contactproduction and sridkat2_contacttest.

    I changed the database.yml accordingly.

    Output of ‘rake migrate’ w/ trace: http://pastebin.com/688626

    In database.yml, this is present: # gem install mysql
    Should that be uncommented? Uncommented and now ‘rake migrate’ says:

    /home/sridkat2/public_html/testapp/public/Contact/config$ rake migrate
    (in /home/sridkat2/public_html/testapp/public/Contact)
    rake aborted!
    syntax error on line 12, col 0: `development:’
    (See full trace by running task with—trace)

    With trace on, this is the output: http://pastebin.com/688630

    Thanks so much for your patience.

     
  36. 36 Robert

    Sorry I haven’t gotten back sooner, I’ve been moving.

    What server are you using? Is the mysql gem installed? You don’t need to uncomment #gem install mysql, just make sure you have the mysql gem installed.

    What is on line 12 of the migrate file for sridkat2_contactdevelopment?

     

Comments closed after 2 weeks.