SapphireSteel Software

 

  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
  -  
     
     
     
     

 

  rss
RSS (SITE)
 
  rss
RSS (BLOG ONLY)
 
   
 
 
     

 

Section :: Rails
- Format For Printing...

How To Create A Blog With Rails 2

by Huw Collingbourne
The Generation Game
Sunday 16 December 2007.
 

I’ve come to regard creating a Blog application as being the Rails equivalent of ‘Hello world’. If you can get to the point of entering and editing a few posts, you know that you are, at least, on the right track. So when I tried following my own Rails 1 Blog tutorial with Rails 2, I was (to say the least) mildly disappointed that the darn’ thing didn’t work!

The point at which everything ground to a halt was when, after having created the model, I ran the generate/scaffold script. In Rails 2, scaffolds don’t work quite as they did in Rails 1. That’s the bad news. The good news is that, when you get your head around the new way of generating scaffolds you’ll find that they can actually cut out a step or two. In this tutorial, I’ll show you how to get a very simple blog application up and running by letting the scaffold generator define the model rather than doing this by running a separate ‘model generator’.

I should say at the outset that I am only starting to learn Rails 2.0. Documentation is rather thin on the ground at the moment and I am, therefore, working things out largely through a process of trial end error. Consequently, this tutorial makes no claim to elegance and it is quite likely that there are all kinds of neat things in Rails 2 which I have failed to mention due to my ignorance ;-).

Even so, if you are having problems getting started with Rails 2, I hope that this may, at least, get you over a few of the initial hurdles...

NOTE: This tutorial assumes that you already have Ruby, Rails, MySQL and Ruby In Steel Developer installed. For more information on installing all the required software, see…
- Setting Up Ruby (and Rails) For Ruby In Steel – From Scratch
- Installing MySQL For Ruby On Rails

1: Create A New Application

These steps are broadly the same in both Rails 1 and Rails 2...

Load up Ruby In Steel Developer (or Trial) edition and follow along…

- Create A New Rails Project

In Visual Studio...
- Select the File menu, New then Project.
- Select Ruby In Steel in the left-hand pane. In the right-hand pane select Rails Project.

- Enter a name such as ‘MyBlogProject’ in the Name field and, optionally, browse to a directory.
- Leave ‘Create directory for solution’ checked.
- Click OK.

- Create The Rails Application

A dialog box pops up to prompt you to select a database server, name your database and host.

Here I assume you are using MySQL. You may use other database servers such as SQL Server (for more information see: Using SQL Server With A Rails Application. But, for the sake of simplicity, I suggest using MySQL with this tutorial.

- Make sure MySQL is selected as the database server.
- Check off the Development and Test database types.
- Now fill out the database settings:

The actual details will vary according to your local settings. You should, for example, enter the host, user name and password (if any) which you have previously specified when setting up your database server:

Database = railsblog
User = root
password = (enter your MySQL password or leave blank if none)
Host = localhost

- Click ‘Test Connection’ to check that all is well. If so, this is what you should see...

(If this produces an error you need to check tat the paths to MySQL are correct (Tools->Options->Projects and Solutions->Ruby In Steel) and that your user name, password and host details are all entered correctly.

- Once you’ve verified the connection, click OK

You should now see a ‘Creation and Import Data’ dialog.

This provides information on the application you are about to create. (Note: this same dialog also appears when you import an existing project in which case, the source directory and file statistics will also be shown).

- Press ‘Proceed’.

The Rails application, complete with a MySQL database, will now be created. After a short wait, you should see all the application’s folders and files appear beneath the project branch in the Solution Explorer.

Verify That Rails Is Running

The easiest way to run an application is by clicking the One-click Rails Debugger or by pressing the F5 function key. This starts the server and runs the application in debugging mode.

- Select One-Click Rails Debugger on the Ruby menu.

Wait a few moments for the server will start. You should see something like this in the Ruby Console (if the Ruby Console isn’t visible, select the View menu then Other Windows, Ruby Console)...

- Press CTRL+W, W to open a web browser inside Visual Studio. Or you may open any standalone browser of your choice. In the address bar enter http://localhost:3000.

NOTE: If you are not using the default port, 3000, you will need to specify the actual port number in the address - e.g. if the server port is 3003, you should enter: http://localhost:3003

All being well, you will now see a ‘Welcome screen’ from Rails, similar to the following:

Now stop the debugger (select Debug, Stop Debugging).

2: Create Scaffolding and Views

These steps are different in Rails 1 and Rails 2...

Instead of creating a model (to define the database) and scaffolding (to create some Ruby code in a ‘controller’ and some basic web page templates in the form of ‘views’), we shall use the new features of the Rails 2 scaffold generator script to create everything in a single operation.

In Rails 1, the generate/scaffold script required two arguments: a model name and a controller name. In rails 2, it only requires the model name. However, if you haven’t already defined a model, you can also pass to the script a list of additional arguments giving the names of the database columns which you wish to create along with their data types following a colon (e.g. to create a ‘title’ column with the string data type you would enter title:string).

Let’s do this now. Make sure the Generator window is displayed...

- Select Generate from the Ruby menu).

- Select scaffold in the list of script actions and enter post in the Script Value(s) edit box. This has the effect of constructing the following script in the field at the bottom of the Generate dialog:

ruby script/generate scaffold post

Rails 2’s scaffold generator requires at least the model name (here post) but it does not require an extra argument (such as blog) to specify a controller name (as it did in Rails 1). As I mentioned earlier, it also lets you create database columns by appending extra name:type arguments.

- Edit the script in the field at the bottom of the Generate dialog so that it matches the following:

ruby script/generate scaffold post title:string body:text created_at:datetime

- Now press Go.

The Generate script will run and you will see its progress in the Script console...

When this is complete, you can run a migration in order to update the database table.

- To do that, select Rake from the Ruby menu.
- In the Rake dialog, select db:migrate in the list of Rake actions.
- Press Go.

Once again, the Script Console will appear. Wait until this shows that the Rake take has completed.

If you expand the branches of the Solution Explorer you will find that you have Generated a number of template files under \app\views and a posts_controller.rb file under \app\controllers. You also have a migration file under \db\migrate.

Now let’s create a new partial.

Right-click the \app\views\posts folder in the Solution Explorer. From the popup menu, select Add->New Item.

- In the dialog box, highlight Empty Ruby/HTML File. In the Name field, enter: _post.html.erb. Click the Add button.

The extension, ‘.html.erb’ is now the default for HTML template files rather than ‘.rhtml’ which was the default Rails 1 extension.

- Double-click _post.html.erb to open it in the editor.
- Add this code:

- Save it.
- Now open show.html.erb.
- Delete this...

<p>
 <b>Title:</b>
 <%=h @post.title %>
</p>

<p>
 <b>Body:</b>
 <%=h @post.body %>
</p>

<p>
 <b>Created at:</b>
 <%=h @post.created_at %>
</p>

- And replace it with this...

This tells Rails to render the _post partial here. The code in the editor should now look like this...

- Save your changes.

And that’s it. Now you can test out the application.

Start the debugger again:

- Click the One-Click Rails Debugger on the Ruby menu (or press F5).
- Wait for the server to start again (check this in the Ruby Console):

- To go back to the browser press CTRL+W,W if necessary) and enter the following address (in the address either use the default port, 3000, or whichever port number you used previously):

http://localhost:3000/posts

You should see your page with its index page active. This is what should appear...

- Now click the New Post link.

- In the New post page, enter a title and some body text. Then click Create.

The next page that displays is the ‘Show page’. This is defined by the combination of the show.html.erb view and the _post.html.erb partial (if you aren’t sure about this, you can easily verify this by adding some text (e.g. ‘partial start’ and ‘partial end’) at the start and end of the partial, like this...

Then refresh the browser...

- Now carry on entering posts and clicking the links to navigate through the various defined views...

This gets us to the same point in Rails 2 as part one of our Rails 1 Blog tutorial. Now you may want to move on and try adapting part two of that tutorial to work with Rails 2. I may return to look at that at some later date...

AddThis Social Bookmark Button


Forum

  • How To Create A Blog With Rails 2
    30 October 2008

    Thanks for this — straight forward and to the point. I think it makes clear the idea that you should have your database plannend out before you start noodling around with a web app. It seems a bit of a disappointment, though. One thing that really impressed me with RoR 1 is that you can use dynamic scaffolds (is that what they are?) and model generation to modify the database as you go along. This seemed really good for Agile development. The RoR 2 scaffold seems static — the good news is that you get code you can build from. The bad news is that modifying the db table isn’t obvious. Do you know the approved approach to this problem? Is it possible to iteratively add or remove db columns in RoR 2? Or do you have to tear down the whole app and start all over again?

    Thanks cud

  • How To Create A Blog With Rails 2
    9 July 2008, by jimmy

    I would love to see Part 2 ported over to Rails 2. I think I can figure it out for myself but I’d love to see someone who really knows what they’re doing do it.

    • How To Create A Blog With Rails 2
      9 July 2008, by Huw Collingbourne

      Thanks for the interest. This is something I will need to do in the course of revising The Book Of Ruby. The Rails section is one of the later chapters, however, so I’ll see if I can find some time (difficult!) to bring that forward a bit...

      best wishes

      Huw

  • How To Create A Blog With Rails 2
    15 May 2008, by Monica

    Hi!

    Thanks for the simple tutorial. But I receive the following error:


    ActionView::ActionViewError in Posts#show Showing posts/show.html.erb where line #1 raised:

    Couldn’t find template file for posts/_post in ["C:/Documents and Settings/monica/My Documents/Visual Studio 2005/Projects/Import1/Blog_on_Rails/app/views"]


    I’ve just installed rails 2.0.

    Please help.

    • How To Create A Blog With Rails 2
      15 May 2008, by Huw Collingbourne

      Without seeing your code, it’s hard to guess where the problem lies. Have you cut and pasted the sample code from this article? If not, you may want to try following through again doing so. It sounds as though there may be a naming error somehwhere in your code. Does the file _post.html.erb actually exist? This should have been created as part of this tutorial. You may want to verify that it was created and is in the expected folder.

      best wishes

      Huw

  • How To Create A Blog With Rails 2
    20 January 2008

    Just wanted to say thank you. Though I don’t use Visual Studio, the this entry helped me a lot. :)

  • How To Create A Blog With Rails 2
    11 January 2008, by Basil Guevarra

    Thanks very much for the RoR v2 tutorial. Excellent starting point! (I followed w/ TextMate just fine — hope to see more tutorials soon!)

  • How To Create A Blog With Rails 2
    5 January 2008, by Sylvain

    Hi,

    I obtained the link to this tutorial from de IRC chanel. Now I will adapt your version into the wiki.

    Thanks for this simple tutorial.

    Sylvain.

    • How To Create A Blog With Rails 2
      5 January 2008, by Huw Collingbourne

      I’m glad it was useful. When I have time, I’ll add some more tutorials...

      best wishes

      Huw

 

© 2009 SapphireSteel Software. All rights reserved