THIS BLOG HAS MOVED TO blog.fearoffish.com

Part 2 of my beginner series focuses on the generator, and models. Many a question has been asked about these bits and bobs because it's alien to those coming from php, java and the like. Hopefully I can clear it up a little bit.

So you've learnt where the files are kept in the rails directory structure, but how do you get the files there? Let's start from the beginning by creating a rails application:

rails funky_chicken

What we've done here is invoked the rails command and told it to create a new application called 'funky_chicken', a rails application name is merely what you'd like the directory to be called, all the files we talked about previously are created within this folder. The next step is to edit our database configuration file to point to our database. If you haven't created one then do so now, I've used mysql and created one called funkychickendevelopment. MySQL is just my database of choice for most projects, you may prefer to use SQLLite, PostgreSQL or another, all major database types are supported.

Why did I call my database funkychickendevelopment? Rails by default assumes you have 3 databases for each stage of development. Development, test and production databases, each serve a different purpose. Have a look at your config/database.yml file and see how to configure them. Be careful not to add tabs to this file because YAML doesn't like them at all.

Side Note: Rails uses convention over configuration, which means that it assumes a lot about your code and naming schemes, but if necessary you can override these defaults. If you learn to use them from day one you'll save yourself a lot of headaches in the future. 90% of the files you create are lowercase and use underscores instead of spaces, the only reason to not follow this rule would be if you already have files that use capitals and spaces, and are unable to change them.

Before we create our first controller it might be best to quickly look at how the cogs turn in a rails app, and explain a little about why. Rails uses the Model-View-Controller paradigm because it separates the different pieces of your application and helps alleviate the coupling that can result from intermixing it all. I won't go into detail because you could just go and read about it at wikipedia. Needless to say you should be familiar with how it works.

In Rails terms it means exactly what it says on the tin. Models interact with your database and contain all the validation and search abilities, you get a lot of this for free with ActiveRecord (The rails library to control access to your database). Views contain the visual part of your application. Controllers knit the two together with your business logic directing the flow.

Let's start shall we, we have a rails application called 'funky_chicken' and it's going to display and count our chickens. You've been in and edited your database configuration to point you to your database, but we haven't got any tables. We're not going to learn about the beauty of migrations today (Manipulating our database with ruby), we'll leave that for another time. So go ahead and run the following SQL on your database:

CREATE TABLE `funky_chickens` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`funkiness` int(11) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Now we have our development database set up to hold our funky chickens as well as store the amount of funkiness each has, we need a controller to accept input from the user:

./script/generate controller welcome

The generate command can create many things for us, in this case we want a controller called welcome. The welcome controller is going to greet our users and offer them a link to our chicken counter (Which we haven't created yet), most methods in our controllers correspond to a view, think of these views as html files. Each view in php would be a php file, so if we wanted an index page (The first page a user sees when they come to a site) we'd call it index.ph and put it at the root of our site. In rails we create an index method and a corresponding index view, then we tell the routing system (A rails method of doing url rewrites without having to know nuclear physics) to point to that index file.

Edit app/controllers/welcome_controller.rb

Add app/views/welcome/index.rhtml

The index.rhtml file is a standard html file in essence but with the added bonus of ruby sprinkles, but that's for another tutorial. The concept you need to be aware of here is that app/views is where we store all the views and welcome/index.rhtml is matching up with our index method within the welcome controller. Go ahead and start the built in development server that rails comes with (Webrick) and then have a look at http://localhost:3000/welcome/

./script/server

So there is our view showing what we've just added, mmmkay? The webrick server by default serves from port 3000 which is why we add that little bit to the end.

Let's move onto models now because it's all well and good having a welcome screen, but what about our funky chickens? Our table in the database is called funky_chickens and not by coincidence, it holds funky chickens. It is using the plural of Funky Chicken and in lowercase, with underscores instead of spaces. It makes sense then, that our model file will be called FunkyChicken. Confused? Well class names in Ruby are capitalised with no spaces and our model is a class, however, later on when we ask a FunkyChicken to tell us how funky it is, it will intelligently convert this capitalised name into lowercase with spaces, like magic.

./script/generate model funky_chicken

We should now have a new model file in app/models called funky_chicken.rb, and if you open it up you'll see our class name:

Our model file is empty but because it inherits from ActiveRecord::Base it is capable of a huge amount, for free. Let's play around with it now and find out what it can do. I'm assuming you understand Ruby here, because if you don't there's loads of resources available at the other end of a google search that will help you out.

[Added to avoid confusion] Scaffolding is the simple way to generate the skeleton of a CRUD page. There are two ways to go about using scaffolding, the first is to simply add 'scaffold :model_name' to the top of your controller and it will create the methods on the fly, or to use what I outline below. Take your pick. The scaffold method below generates the controller and model so you don't have to, but if you have it will ask to overwrite it.

We could create a controller to manage our chickens for us and we could create the methods for adding/editing/deleting our chickens to this manually, but instead let's use a generator called scaffold to save us the time for this tutorial, it will do it all for us:

./script/generate scaffold funky_chicken chickens

If it asks you to overwrite the existing files just press Enter, we haven't added anything to them so it should be okay, but if you had changed them this would wipe your changes out, be aware of that. If we didn't already have a funky_chicken model this would have created it for us, but we do. It has, however, created a new controller for us called chickens and in that controller (if you have a gander) it has created methods to do everything we need to our chickens. Have a look in your browser at http://localhost:3000/chickens.

Oh wow, we can add/edit/delete chickens and we haven't done anything, how smashingly cool?

That's enough for today, have a little browse at the views and controller methods that the scaffold has added for you with the new understanding you have of how it knits together.

In the next part of this tutorial series we're going to look at tests because I feel they are one of the most important aspects of rails that let's you leverage the power of rails to give piece of mind for changes you make. Test Driven Development is encouraged in Ruby on Rails and so that's our next step.

Let me know what you think of this tutorial and the series as it goes along, and also what can I do to improve it?

If you like this tutorial, please digg it so others will find it helpful too.

Sorry, comments are closed for this article.

Jamie van Dyke

Jamie van Dyke has been a Rails developer since the beginning of 2005, working with some of the major players in the web market. He also played a large part in the documenting of Rails for the Caboose Documentation Project and teaches others on his blog and in training sessions around the world. Jamie is a core Rails contributor, and the publisher of multiple gems and plugins.

I'm a father of 2, living in a little village called Skipton which is in North Yorkshire, England. Anything else you'd like to know you can ask. Check out my photo and info at the caboose facebook or my flickr page.

Jamie is also unsure why he must write a Bio in third person, and doesn't really have a fear of fish, he just dislikes the taste and smell of them.

< Recommend me on Working With Rails >

Search


Email:     


or    Subscribe in a Reader




 

Recommended Services

Basecamp project management and collaboration

Recommended Books